在C中打印字符串的一部分
有没有办法只打印部分字符串?
例如,如果我有
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