how to empty string in c
To empty a string in C, you can use the strcpy()
function from the <string.h>
library. Here's an example:
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello, World!"; // Initialize the string
printf("Before emptying: %s\n", str);
strcpy(str, ""); // Empty the string
printf("After emptying: %s\n", str);
return 0;
}
This code declares a character array str
and initializes it with the string "Hello, World!". The strcpy()
function is then used to copy an empty string ""
into str
, effectively emptying it. Finally, the emptied string is printed before and after the emptying operation.
Output:
Before emptying: Hello, World!
After emptying:
Note that the strcpy()
function is used here to demonstrate how to empty a string. However, it is worth mentioning that the safer approach would be to use strncpy()
to specify the number of characters to copy, ensuring that the destination string is properly terminated.