C language judges that the string is empty

Original: https://blog.csdn.net/selina8921/article/details/79176297

Generally speaking, we are used to using a character array to store a string.

char str_array[LEN];

Or malloc a piece of memory to store a string

char * str_ptr = (char *) malloc (LEN * sizeof (char));

After defining the array or character pointer, you need to do an initialization, otherwise it will be a random value, and you will not be able to determine whether the changed string is empty in the future.

So, first of all, make sure that the string is initialized to empty

memset(str_ptr,’\0’,sizeof(LEN*sizeof(char)));

For a string that has been initialized, we can use strlen to determine whether it is empty.

strlen() starts counting from the 0th character of the string, and stops when it encounters the character \0, and gets the length of the string. If the length is 0, the string is empty.

Regardless of the constant string const char* hi_str = "Hi str";

Or for string variables char * str;

We can all use

if (str != NULL) {

if (strlen(str) == 0) {

    // it is empty string

}

}

To judge.

Avoid using if (str[0] =='\0') to judge, because it may cause crash.

Note:
If it is a string pointer, first determine whether the pointer is empty, otherwise it is easy to cause a segmentation fault.
Develop a good habit and first initialize the variable after defining it

Guess you like

Origin blog.csdn.net/xiaolei251990/article/details/84583453