[英]What's the best way to reset a char[] in C?
I use a string: 我用一个字符串:
char word[100];
I add some chars to each position starting at 0. But then I need be able to clear all those positions so that I can start add new characters starting at 0. 我从0开始为每个位置添加一些字符。但是我需要能够清除所有这些位置,以便我可以从0开始添加新字符。
If I don't do that then if the second string is shorten then the first one I end up having extra characters from the first string when adding the second one since I don't overwrite them. 如果我不这样做,那么如果第二个字符串缩短,那么第一个字符串在添加第二个字符串时最终会从第一个字符串中获得额外的字符,因为我没有覆盖它们。
如果要将整个数组清零,可以:
memset(word, 0, sizeof(word));
You don't need to clear them if you are using C-style zero-terminated strings. 如果使用C样式的零终止字符串,则无需清除它们。 You only need to set the element after the final character in the string to NUL ('\\0').
您只需要将字符串中最后一个字符后面的元素设置为NUL('\\ 0')。
For example, 例如,
char buffer[30] = { 'H', 'i', ' ', 'T', 'h', 'e', 'r', 'e', 0 }; // or, similarly: // char buffer[30] = "Hi There"; // either example will work here. printf("%s", buffer); buffer[2] = '\0'; printf("%s", buffer)
will output 将输出
Hi There
嗨,您好
Hi你好
even though it is still true that buffer[3] == 'T'
. 即使
buffer[3] == 'T'
仍然是真的。
strcpy(word,"")
也可用于此目的。
*word = '\\0';
额外的东西超过了15个字符的发布限制滚动眼睛 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.