如何检查 char* 变量是否指向空字符串? [英] How can I check if char* variable points to empty string?
问题描述
如何检查 char*
变量是否指向空字符串?
How can I check if char*
variable points to an empty string?
推荐答案
检查第一个字符是否为' '.您还应该检查您的指针是否为 NULL.
Check if the first character is ' '. You should also probably check if your pointer is NULL.
char *c = "";
if ((c != NULL) && (c[0] == ' ')) {
printf("c is empty
");
}
您可以将这两个检查放在一个函数中,以使其方便且易于重用.
You could put both of those checks in a function to make it convenient and easy to reuse.
在 if 语句中可以这样理解,如果 c 不为零且字符数组 'c' 的第一个字符不是 ' ' 或零,则...".
In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not ' ' or zero, then...".
&&
只是简单地结合了这两个条件.基本上就是这样说的:
The &&
simply combines the two conditions. It is basically like saying this:
if (c != NULL) { /* AND (or &&) */
if (c[0] == ' ') {
printf("c is empty
");
}
}
如果您不清楚这一点,您可能希望获得一本好的 C 编程书籍.我可以推荐一本名为《The C Programming Language》的书.
You may want to get a good C programming book if that is not clear to you. I could recommend a book called "The C Programming Language".
与上述等效的最短版本是:
The shortest version equivalent to the above would be:
if (c && !c[0]) {
printf("c is empty
");
}
这篇关于如何检查 char* 变量是否指向空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!