打印一个字符串

时间:2012-03-09 09:30:20

标签: c

是否有任何功能可以将字符串打印到空间, 例如

char* A = "This is a string."
print(A+5);
output: is

我不想逐个字符地打印。

2 个答案:

答案 0 :(得分:4)

printf("%s", buf)打印buf中的字符,直到遇到空终止符:无法更改该行为。

不能逐字符打印的可能解决方案不会修改要打印的字符串,并使用格式说明符%.*s来打印字符串中的第一个N字符:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* s = "this is a string";
    char* space_ptr = strchr(s, ' ');

    if (0 != space_ptr)
    {
        printf("%.*s\n", space_ptr - s, s);
    }
    else
    {
        /* No space - print all. */
        printf("%s\n", s);
    }

    return 0;
}

输出:

  

答案 1 :(得分:1)

istream_iterator在空格上进行标记:

#include <sstream>
#include <iostream>
#include <iterator>

int main()
{
  const char* f = "this is a string";
  std::stringstream s(f);
  std::istream_iterator<std::string> beg(s);
  std::istream_iterator<std::string> end;
  std::advance(beg, 3);
  if(beg != end)
    std::cout << *beg << std::endl;
  else
    std::cerr << "too far" << std::endl;
  return 0;
}
相关问题