How to check if C string is empty
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:
I want the program to stop looping if the user just presses enter without entering anything.
![]()
13 Answers 13
Since C-style strings are always terminated with the null character ( \0 ), you can check whether the string is empty by writing
Alternatively, you could use the strcmp function, which is overkill but might be easier to read:
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!
If you want to check if a string is empty:
If the first character happens to be ‘\0’ , then you have an empty string.
This is what you should do:
You can check the return value from scanf . This code will just sit there until it receives a string.
Typically speaking, you’re going to have a hard time getting an empty string here, considering %s ignores white space (spaces, tabs, newlines). but regardless, scanf() actually returns the number of successful matches.
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+z for example) you can just check the return result.
Note you have to check less than because in the example I gave, you’d get back -1 , again detailed in the man page:
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.
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.Empty (A constant for empty strings).
Syntax:
Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False.
Example:
Program: To demonstrate the working of the IsNullOrEmpty() Method :
С# как выбрать то, что оказалось пустым?
При работе с данными в C# иногда возникает необходимость проверить, пустое ли значение находится в переменной, массиве или коллекции. Пустые значения могут возникать по разным причинам, например, если пользователь оставил поле ввода пустым или если при чтении данных из файла возникла ошибка. В этой статье мы рассмотрим различные способы проверки на пустое значение в C#.
Проверка на null
Первым нашим инструментом будет проверка на null. Null – это особое значение, которое в C# используется для обозначения отсутствия значения. Если переменная равна null, значит, в нее не было записано никакое значение. Для проверки на null в C# используется ключевое слово null . Вот как это выглядит в коде:
В этом примере мы создаем строковую переменную text и задаем ей значение null. Затем мы проверяем, равна ли переменная null, и выводим сообщение, если это так.
Проверка на пустую строку
Если мы работаем со строками, то еще одной причиной того, что строка может быть пустой, является отсутствие символов в строке. Для проверки на пустоту строки можно использовать метод string.IsNullOrEmpty или метод string.IsNullOrWhiteSpace .
Метод string.IsNullOrEmpty проверяет на пустоту и на null, а метод string.IsNullOrWhiteSpace проверяет на пустоту, на null и на наличие только пробельных символов. Вот как это выглядит в коде:
В этом примере мы создаем две переменные – строковые переменные text и text2 . В первой строке мы задаем переменной text пустое значение, а во второй – значение, состоящее только из пробельных символов. Затем мы проверяем обе строки с помощью методов string.IsNullOrEmpty и string.IsNullOrWhiteSpace , и если строка пустая или равна null, выводим сообщение.
Проверка на пустой массив или коллекцию
Если мы работаем со списком значений, то еще одним вариантом пустого значения может быть пустой массив или коллекция. Для проверки на пустоту массива или коллекции мы можем использовать свойство Length или метод Enumerable.Any .
Свойство Length позволяет получить количество элементов в массиве. Если массив пустой, то его длина будет равна 0. Метод Enumerable.Any , в свою очередь, позволяет проверить, есть ли хотя бы один элемент в коллекции. Если коллекция пустая, то метод вернет значение false . Вот как это выглядит в коде:
В этом примере мы создаем пустой массив array и пустую коллекцию list . Затем мы проверяем оба объекта на пустоту, используя свойство Length для массива и метод Enumerable.Any для коллекции, и выводим сообщение, если объект пустой.
Заключение
Проверка на пустое значение является важной задачей при работе с данными в C#. В этой статье мы рассмотрели различные способы проверки на пустое значение, такие как проверка на null, на пустую строку, на пустой массив и на пустую коллекцию. При выборе метода проверки необходимо учитывать тип данных и особенности работы с ними.
How to check if a string is really empty with C#
Is a string empty? What if it contains only white spaces? You shouldn’t reinvent the wheel, since .NET exposes methods exactly for these cases: String.IsNullOrEmpty and String.IsNullOrWhiteSpace.
Table of Contents
To be, or not to be (empty), that is the question…
That’s a simple, yet complex, question.
First of all, when a string is not empty? For me, when there is at least one character or one number.
Do it from scratch
Let’s create a custom function to achieve this functionality.
Ok, now we have to think of how to check if the string myString is empty.
Of course, the string must be not null. And must not be empty. Maybe… its length must be greater than zero?
Ok, we should be fine. But, what if the string contains only whitespaces?
I mean, the string " " , passed to the IsStringEmpty method, will return true.
If that’s not what we want, we should include this check on the method.
Of course, this implies a bit of complexity to check null values.
Ok, we covered the most important scenarios.
So we can try the method with our values:
Fine. Too tricky, isn’t it? And we just reinvented the wheel.
.NET native methods: String.IsNullOrEmpty and String.IsNullOrWhitespace
C# provides two methods to achieve this result, String.IsNullOrEmpty and String.IsNullOrWhiteSpace, with a subtle difference.
String.IsNullOrEmpty checks only if the string passed as parameter has at least one symbol, so it doesn’t recognize strings composed by empty characters.
String.IsNullOrWhitespace covers the scenario described in this post. It checks both empty characters and for escape characters.
You can see a live example here.
This article first appeared on Code4IT
Wrapping up
As you can see, out of the box .NET provides easy methods to handle your strings. You shouldn’t reinvent the wheel when everything is already done.