C语言 在 C 中打印字符串的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4841219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:40:07  来源:igfitidea点击:

Print part of a string in C

cc-strings

提问by Mark

Is there a way to only print part of a string?

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

For example, if I have

例如,如果我有

char *str = "hello there";

Is there a way to just print "hello", keeping in mind that the substring I want to print is variable length, not always 5 chars?

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

I know that I could use a forloop and putcharor that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?

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

回答by Jerry Coffin

Try this:

尝试这个:

int length = 5;
printf("%*.*s", length, length, "hello there");

回答by Mehrdad Afshari

This will work too:

这也将起作用:

fwrite(str, 1, len, stdout);

It will not have the overhead of parsing the format specifier. Obviously, to adjust the beginning of the substring, you can simply add the index to the pointer.

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

回答by Chris Charabaruk

You can use strncpyto duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpywon't do that if it doesn't encounter one in the source string. A better solution, as Jerry Coffin pointed out, is using the appropriate *printffunction to write out or copy the substring you want.

您可以使用strncpy复制要打印的字符串部分,但必须注意添加空终止符,因为strncpy如果在源字符串中没有遇到空终止符,则不会这样做。正如 Jerry Coffin 指出的那样,更好的解决方案是使用适当的*printf函数来写出或复制您想要的子字符串。

While strncpycan be dangerous in the hands of someone not used to it, it can be quicker in terms of execution time compared to a printf/sprintf/fprintfstyle solution, since there is none of the overhead of dealing with the formatting strings. My suggestion is to avoid strncpyif you can, but it's good to know about just in case.

虽然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

回答by farfromhome

printfand friends work well when that's all you want to do with the partial string, but for a more general solution:

printf和friends 在您只想对部分字符串进行处理时效果很好,但对于更通用的解决方案:

char *s2 = s + offset;
char c = s2[length]; // Temporarily save character...
s2[length] = '##代码##';   // ...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