有没有办法只打印部分字符串?
例如,如果我有
char *str = "hello there";
Run Code Online (Sandbox Code Playgroud)
有没有办法只打印"hello",请记住我要打印的子字符串是可变长度,而不是总是5个字符?
我知道我可以使用一个for循环,putchar或者我可以复制数组,然后添加一个空终止符,但我想知道是否有更优雅的方式?
Jer*_*fin 31
试试这个:
int length = 5;
printf("%*.*s", length, length, "hello there");
Run Code Online (Sandbox Code Playgroud)
Meh*_*ari 17
这也可以:
fwrite(str, 1, len, stdout);
Run Code Online (Sandbox Code Playgroud)
它不会有解析格式说明符的开销.显然,要调整子字符串的开头,您只需将索引添加到指针即可.