How to clear a string in C language?
In C language, you can use the following methods to clear a string:
- Copy the string
#include <stdio.h>
#include <string.h>
int main() {
char str[100] = "Hello World";
printf("Before clearing: %s\n", str);
strcpy(str, ""); // 使用空字符串清空字符串
printf("After clearing: %s\n", str);
return 0;
}
- I only need one choice.
#include <stdio.h>
#include <string.h>
int main() {
char str[100] = "Hello World";
printf("Before clearing: %s\n", str);
for(int i = 0; i < strlen(str); i++) {
str[i] = '\0'; // 使用空字符清空字符串
}
printf("After clearing: %s\n", str);
return 0;
}
Regardless of the method used, it is possible to clear the string and reset it to an empty string.