Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if C string is empty

Tags:

c

string

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:

#include <stdio.h> #include <string>  int main() {   char url[63] = {'\0'};   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.

like image 908
codedude Avatar asked Mar 18 '13 19:03

codedude


People also ask

How do you test if a string is empty in C?

To check if a given string is empty or not, we can use the strlen() function in C. The strlen() function takes the string as an argument and returns the total number of characters in a given string, so if that function returns 0 then the given string is empty else it is not empty.

How do you check if a value is an empty string?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

How do you check if a string is null or empty in C#?

C# | IsNullOrEmpty() Method In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.

Is there an empty character in C?

You can use c[i]= '\0' or simply c[i] = (char) 0 . The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero. Yes, and there is no "empty char".


2 Answers

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

do {    ... } while (url[0] != '\0'); 

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

do {    ... } while (strcmp(url, "")); 

Note that strcmp returns 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.

Hope this helps!

like image 96
templatetypedef Avatar answered Oct 03 '22 11:10

templatetypedef


If you want to check if a string is empty:

if (str[0] == '\0') {     // your code here } 
like image 45
nabroyan Avatar answered Oct 03 '22 11:10

nabroyan