我一直在用C语言开发一个项目,需要我大量使用字符串。 通常情况下,我使用C ++编程,所以这与仅说string.empty()有点不同。
我想知道在C中清空字符串的正确方法是什么?会是这样吗?
buffer[80] = "Hello World!\n"; // ... strcpy(buffer, "");I've been working on a project in C that requires me to mess around with strings a lot. Normally, I do program in C++, so this is a bit different than just saying string.empty().
I'm wondering what would be the proper way to empty a string in C. Would this be it?
buffer[80] = "Hello World!\n"; // ... strcpy(buffer, "");最满意答案
这取决于你的意思是“空”。 如果你只是想要一个零长度的字符串,那么你的例子将工作。
这也将起作用:
buffer[0] = '\0';如果你想把字符串的全部内容清零,你可以这样做:
memset(buffer,0,strlen(buffer));但是这只会用于调零至第一个NULL字符。
如果字符串是一个静态数组,你可以使用:
memset(buffer,0,sizeof(buffer));It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.
This will also work:
buffer[0] = '\0';If you want to zero the entire contents of the string, you can do it this way:
memset(buffer,0,strlen(buffer));but this will only work for zeroing up to the first NULL character.
If the string is a static array, you can use:
memset(buffer,0,sizeof(buffer));更多推荐
发布评论