C语言 如何检查C字符串是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15485179/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:45:46  来源:igfitidea点击:

How to check if C string is empty

cstring

提问by codedude

I'm writing a very small program in C that needs to check if a certain string is empty. For the sake of this question, I've simplified my code:

我正在用 C 编写一个非常小的程序,需要检查某个字符串是否为空。为了这个问题,我简化了我的代码:

#include <stdio.h>
#include <string>

int main() {
  char url[63] = {'
do {
   ...
} while (url[0] != '
do {
   ...
} while (strcmp(url, ""));
');
'}; do { printf("Enter a URL: "); scanf("%s", url); printf("%s", url); } while (/*what should I put in here?*/); return(0); }

I want the program to stop looping if the user just presses enter without entering anything.

如果用户只按 Enter 键而不输入任何内容,我希望程序停止循环。

回答by templatetypedef

Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing

由于 C 风格的字符串总是以空字符 ( \0) 结束,你可以通过写来检查字符串是否为空

if (str[0] == '
do {
    /* 
    *   Resetting first character before getting input.
    */
    url[0] = '
int count = 0;
do {
  ...
  count = scanf("%62s", url);  // You should check return values and limit the 
                               // input length
  ...
} while (count <= 0)
'; // code } while (url[0] != '
int a;

do {
  // other code
  a = scanf("%s", url);

} while (a <= 0);
');
') { // your code here }

Alternatively, you could use the strcmpfunction, which is overkill but might be easier to read:

或者,您可以使用该strcmp函数,这有点矫枉过正,但可能更容易阅读:

*url == '
if (string[0] == '
do {
   ...
} while (url[0] != '
do {
    if (!fgets(url, sizeof url, stdin)) /* error */;
    /* ... */
} while (*url != '\n');
')
') { }
'

Note that strcmpreturns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.

请注意,strcmp如果字符串不同,则返回一个非零值,如果它们相同,则返回 0,因此此循环将继续循环,直到字符串为非空。

Hope this helps!

希望这可以帮助!

回答by nabroyan

If you want to check if a string is empty:

如果要检查字符串是否为空:

do {
    // Something
} while (*url);

回答by Mohamad Ali Baydoun

If the first character happens to be '\0', then you have an empty string.

如果第一个字符恰好是'\0',则您有一个空字符串。

This is what you should do:

这是你应该做的:

#define IS_EMPTY_STR(X) ( (1 / (sizeof(X[0]) == 1))/*type check*/ && !(X[0])/*content check*/)

回答by Mike

Typically speaking, you're going to have a hard time getting an empty string here, considering %signores white space (spaces, tabs, newlines)... but regardless, scanf()actually returns the number of successful matches...

通常来说,考虑到%s忽略空格(空格、制表符、换行符),您将很难在这里获得空字符串……但无论如何,scanf()实际上返回成功匹配的数量……

From the man page:

从手册页:

the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

成功匹配和分配的输入项的数量,可以少于提供的数量,或者在早期匹配失败的情况下甚至为零。

so if somehow they managed to get by with an empty string (ctrl+zfor example) you can just check the return result.

因此,如果他们以某种方式设法使用空字符串(ctrl+z例如),您只需检查返回结果即可。

while (! IS_EMPTY_STR(url));

Note you have to check less than because in the example I gave, you'd get back -1, again detailed in the man page:

请注意,您必须检查的次数少于因为在我给出的示例中,您会返回-1,在手册页中再次详细说明:

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

如果在第一次成功转换或匹配失败发生之前到达输入末尾,则返回值 EOF。如果发生读取错误,也会返回 EOF,在这种情况下,流的错误指示符(请参阅 ferror(3))被设置,并且 errno 被设置指示错误。

回答by squiguy

You can check the return value from scanf. This code will just sit there until it receives a string.

您可以从 中检查返回值scanf。这段代码会一直放在那里,直到它收到一个字符串。

##代码##

回答by flyingOwl

strlen(url)

strlen(url)

Returns the length of the string. It counts all characters until a null-byte is found. In your case, check it against 0.

返回字符串的长度。它计算所有字符,直到找到空字节。在您的情况下,将其检查为 0。

Or just check it manually with:

或者只是手动检查它:

##代码##

回答by Rahul Tripathi

You can try like this:-

你可以这样试试:-

##代码##

In your case it can be like:-

在你的情况下,它可能是这样的:-

##代码##

;

;

回答by pmg

First replace the scanf()with fgets()...

首先更换scanf()fgets()...

##代码##

回答by Haroldo_OK

The shortest way to do that would be:

做到这一点的最短方法是:

##代码##

Basically, *urlwill return the char at the first position in the array; since C strings are null-terminated, if the string is empty, its first position will be the character '\0', whose ASCII value is 0; since C logical statements treat every zero value as false, this loop will keep going while the first position of the string is non-null, that is, while the string is not empty.

基本上,*url将返回数组中第一个位置的字符;由于 C 字符串是空终止的,如果字符串为空,它的第一个位置将是字符'\0',其 ASCII 值为0; 由于 C 逻辑语句将每个零值视为false,因此该循环将在字符串的第一个位置非空时继续运行,即当字符串不为空时。

Recommended readings if you want to understand this better:

如果你想更好地理解这一点,推荐阅读:

回答by user1537765

I've written down this macro

我已经写下了这个宏

##代码##

so it would be

所以它会

##代码##

The benefit in this macro it that it's type-safe. You'll get a compilation error if put in something other than a pointer to char.

这个宏的好处是它是类型安全的。如果放入指向 char 的指针以外的内容,您将收到编译错误。