C语言 如何检查 char* 变量是否指向空字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7970617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if char* variable points to empty string?
提问by Aan
How can I check if char*variable points to an empty string?
如何检查char*变量是否指向空字符串?
回答by codemaker
Check if the first character is '\0'. You should also probably check if your pointer is NULL.
检查第一个字符是否为'\0'。您可能还应该检查您的指针是否为 NULL。
char *c = "";
if ((c != NULL) && (c[0] == 'if (c != NULL) { /* AND (or &&) */
if (c[0] == 'if (c && !c[0]) {
printf("c is empty\n");
}
') {
printf("c is empty\n");
}
}
')) {
printf("c is empty\n");
}
You could put both of those checks in a function to make it convenient and easy to reuse.
您可以将这两项检查放在一个函数中,以方便且易于重用。
Edit: In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not '\0' or zero, then...".
编辑:在 if 语句中可以这样读,“如果 c 不为零并且字符数组 'c' 的第一个字符不是 '\0' 或零,则...”。
The &&simply combines the two conditions. It is basically like saying this:
在&&简单地结合了两个条件。基本上就像这样说:
if (*ptr == 0) // empty string
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".
如果您不清楚,您可能想要一本好的 C 编程书。我可以推荐一本名为“C 编程语言”的书。
The shortest version equivalent to the above would be:
与上述等效的最短版本是:
if (strlen(ptr) == 0) // empty string
回答by Mark Ransom
My preferred method:
我的首选方法:
if (!*ptr) { /* empty string */}
Probably more common:
可能更常见:
if (*ptr) { /* not empty */ }
回答by Alok Save
Check the pointer for NULLand then using strlento see if it returns 0.NULLcheck is important because passing NULLpointer to strleninvokes an Undefined Behavior.
检查指针 for NULL,然后使用strlen以查看它是否返回0。NULLcheck 很重要,因为将NULL指针传递给strlen调用Undefined Behavior。
回答by Basile Starynkevitch
An empty string has one single null byte. So test if (s[0] == (char)0)
空字符串有一个空字节。所以测试if (s[0] == (char)0)
回答by bhuwansahni
I would prefer to use the strlen function as library functions are implemented in the best way.
我更喜欢使用 strlen 函数,因为库函数是以最好的方式实现的。
So, I would write if(strlen(p)==0) //Empty string
所以,我会写 if(strlen(p)==0) //Empty string
回答by ikm104
Give it a chance:
给它一个机会:
Try getting string via function gets(string) then check condition as if(string[0] == '\0')
尝试通过函数 gets(string) 获取字符串然后检查条件 if(string[0] == '\0')
回答by alvin
similarly
相似地
##代码##
