15

有没有办法只打印字符串的一部分?

例如,如果我有

char *str = "hello there";

有没有办法只打印"hello",请记住我要打印的子字符串是可变长度的,而不总是 5 个字符?

我知道我可以使用for循环,putchar或者我可以复制数组然后添加一个空终止符,但我想知道是否有更优雅的方法?

4

4 回答 4

35

尝试这个:

int length = 5;
printf("%*.*s", length, length, "hello there");
于 2011-01-30T04:55:42.847 回答
21

这也可以:

fwrite(str, 1, len, stdout);

它不会有解析格式说明符的开销。显然,要调整子字符串的开头,只需将索引添加到指针即可。

于 2011-01-30T04:58:47.560 回答
1

您可以使用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
于 2011-01-30T04:59:14.983 回答
0

当您只想对部分字符串执行此操作时,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
于 2011-01-30T05:02:04.797 回答