有没有办法只打印字符串的一部分?
例如,如果我有
char *str = "hello there";
有没有办法只打印"hello"
,请记住我要打印的子字符串是可变长度的,而不总是 5 个字符?
我知道我可以使用for
循环,putchar
或者我可以复制数组然后添加一个空终止符,但我想知道是否有更优雅的方法?
尝试这个:
int length = 5;
printf("%*.*s", length, length, "hello there");
这也可以:
fwrite(str, 1, len, stdout);
它不会有解析格式说明符的开销。显然,要调整子字符串的开头,只需将索引添加到指针即可。
您可以使用strncpy
复制要打印的字符串部分,但您必须注意添加空终止符,因为strncpy
如果它在源字符串中没有遇到空终止符,则不会这样做。正如 Jerry Coffin 所指出的,一个更好的解决方案是使用适当的*printf
函数来写出或复制您想要的子字符串。
虽然strncpy
在不习惯它的人手中可能很危险,但与printf
/ sprintf
/fprintf
样式解决方案相比,它在执行时间方面可能更快,因为没有处理格式化字符串的开销。我的建议是尽可能避免strncpy
,但最好了解一下以防万一。
size_t len = 5;
char sub[6];
sub[5] = 0;
strncpy(sub, str + 5, len); // char[] to copy to, char[] to copy from(plus offset
// to first character desired), length you want to copy
当您只想对部分字符串执行此操作时,printf和朋友工作得很好,但对于更通用的解决方案:
char *s2 = s + offset;
char c = s2[length]; // Temporarily save character...
s2[length] = '\0'; // ...that will be replaced by a NULL
f(s2); // Now do whatever you want with the temporarily truncated string
s2[length] = c; // Finally, restore the character that we had saved