打印一个字符串
问题描述:
答
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;
}
输出:
这
+0
这就是我想的,谢谢 – Deepak 2012-03-09 09:38:26
答
一个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;
}
当然不是,你必须编写自己的函数 – 2012-03-09 09:33:32
Malloc一个新的字符串长度与传入的字符串相同。将char-by-char复制到新字符串中,直到找到空格,然后写入\ 0。 printf新的字符串,然后释放它。 – 2012-03-09 09:37:34
“我不想按字符打印字符。”对不起,所有的C函数,不管是它们的库函数还是你自己制作的,都是逐字打印的。如果你不想要这个,你不能用C语言打印任何东西。 – Lundin 2012-03-09 09:38:55