Cpp check string is empty

Check if String is Empty in C++

In this article, we will discuss different ways to check if a string is empty or not in C++.

Table of Contents

Check if String is Empty in C++ using string::empty()

In C++, the string class provides a member function empty(), which returns True if the length of the calling string object is 0, otherwise returns False. Let’s use this to check if String is Empty or not in following examples,

#include int main() < std::string sample_str = ""; // Check if string is empty if ( sample_str.empty() ) < std::coutelse < std::coutreturn 0; >

Frequently Asked:

Are you a C++ programmer eager to step up your game?

Master the intricacies of C++/C++11/C++20 with our handpicked list of the Best Courses to Learn Modern C++11, C++17 and C++20. Sharpen your skills, conquer complex algorithms, and stand out in your professional or academic sphere.

Читайте также:  Check for environment variable php

This isn’t just about learning — it’s about transforming into the programmer you aspire to be. So, why wait?

Your leap towards programming excellence is just a click away.

If the string contains any character then the empty() function will return False.

Check if String is Empty in C++ using string::size()

In C++, the string class provides a member function size(), which returns the length of the string in bytes. If string is empty, then the size() function will return 0. Let’s use this to check if String is Empty or not in following examples,

#include int main() < std::string sample_str = ""; // Check if string is empty if ( sample_str.size() == 0 ) < std::coutelse < std::coutreturn 0; >
#include int main() < std::string sample_str = "Sample String"; // Check if string is empty if ( sample_str.size() == 0 ) < std::coutelse < std::coutreturn 0; >

If the string contains any character then the value returned by size() function will be more than 0.

Check if String is Empty in C++ using string::length()

In C++, the string class provides a member function length(), which returns the length of the string in bytes. If string is empty, then the length () function will return 0. Let’s use this to check if String is Empty or not in following examples,

#include int main() < std::string sample_str = ""; // Check if string is empty if ( sample_str.length() == 0 ) < std::coutelse < std::coutreturn 0; >
#include int main() < std::string sample_str = "Some sample text"; // Check if string is empty if ( sample_str.length() == 0 ) < std::coutelse < std::coutreturn 0; >

If the string contains any character then the value returned by length() function will be more than 0.

Check if String is Empty in C++ using strlen()

Using the c_str() member function of string, get the char pointer and pass that to the strlen() function. If it returns 0, then it means string is empty. Let’s understand this with some examples,

#include #include int main() < std::string sample_str = ""; // Check if string is empty if (strlen(sample_str.c_str()) == 0 ) < std::coutelse < std::coutreturn 0; >
#include #include int main() < std::string sample_str = "This is a sample"; // Check if string is empty if (strlen(sample_str.c_str()) == 0 ) < std::coutelse < std::coutreturn 0; >

We learned about four different ways to check if a string is empty in C++.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Определить, пуста ли строка в C++

В этом посте мы обсудим, как определить, пуста ли строка в C++.

1. Использование string::empty

Стандартный способ определить, пуста строка или нет, — использовать string::empty функция. Он возвращается true если его длина равна 0, false в противном случае. Например,

результат:

String is empty

2. Использование string::size

The string::size Функция возвращает количество байтов в строке. Пустая строка будет иметь размер 0. Ее можно использовать следующим образом:

результат:

String is empty

3. Использование string::length

The string::length Функция возвращает длину строки в байтах. Это псевдоним string::size функция.

результат:

String is empty

Это все, что касается определения того, пуста ли строка в C++.

Средний рейтинг 5 /5. Подсчет голосов: 1

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Checking if a string is empty in C++

In this tutorial, we are going to learn about how to check if a string is empty or not in C++.

To check if a string is empty or not, we can use the built-in empty() function in C++.

The empty() function returns 1 if string is empty or it returns 0 if string is not empty.

#include #include using namespace std; int main()  string user = ""; if(user.empty()) cout  <"user string is empty"; >else cout  <"user string is not empty "; > return 0; >

Similarly, we can also use the length() function to check if a given string is empty or not.

#include #include using namespace std; int main()  string user = ""; if(user.length() === 0) cout  <"user string is empty"; >else cout  <"user string is not empty "; > return 0; >

or we can use the size() function.

#include #include using namespace std; int main()  string user = ""; if(user.size() === 0) cout  <"user string is empty"; >else cout  <"user string is not empty "; > return 0; >

Note: The length() or size() functions returns the total number of characters in a given string.

Источник

Check if String Is Empty in C++

Check if String Is Empty in C++

  1. Use Built-In Method empty() to Check if String Is Empty in C++
  2. Use Custom Defined Function With size to Check if String Is Empty in C++
  3. Use the strlen() Function to Check if String Is Empty in C++

This article will introduce multiple methods about how to check for an empty string in C++.

Use Built-In Method empty() to Check if String Is Empty in C++

The std::string class has a built-in method empty() to check if the given string is empty or not. This method is of type bool and returns true when the object does not contain characters. The empty() method does not take any argument and implements a constant time complexity function.

Note that even if the string is initialized with an empty string literal — «» , the function still returns the true value. Thus, the empty() function checks for the size of the string and essentially returns the evaluation of the expression — string.size() == 0 .

#include #include #include  using std::cout; using std::endl; using std::cin; using std::string;  int main()   string string1("This is a non-empty string");  string string2;   string1.empty() ?  cout  <"[ERROR] string is empty!"  <endl :  cout  <"string value: "      string2.empty() ?  cout  <"[ERROR] string is empty!"  <endl :  cout  <"string value: "      return EXIT_SUCCESS; > 
string value: This is a non-empty string [ERROR] string is empty! 

Use Custom Defined Function With size to Check if String Is Empty in C++

The previous method could be implemented by the user-defined function that takes a single string argument and checks if it is empty. This function would mirror the behavior of the empty method and return a bool value. The following example demonstrates the same code example with the custom-defined function checkEmptyString . Notice that the function contains only one statement as the return type of the comparison expression would be boolean, and we can directly pass that to the return keyword.

#include #include #include  using std::cout; using std::endl; using std::cin; using std::string;  bool checkEmptyString(const string &s)   return s.size() == 0; >  int main()   string string1("This is a non-empty string");  string string2;   checkEmptyString(string1) ?  cout  <"[ERROR] string is empty!"  <endl :  cout  <"string value: "      checkEmptyString(string2) ?  cout  <"[ERROR] string is empty!"  <endl :  cout  <"string value: "      return EXIT_SUCCESS; > 
string value: This is a non-empty string [ERROR] string is empty! 

Use the strlen() Function to Check if String Is Empty in C++

The strlen() function is part of the C string library and can be utilized to retrieve the string’s size in bytes. This method could be more flexible for both string and char* type strings that may come up in the codebase. strlen takes const char* argument and calculates the length excluding the terminating \0 character.

Note that the program’s structure is similar to the previous methods, as we define a separate boolean function and declare the only parameter it takes as const char* .

#include #include #include  using std::cout; using std::endl; using std::cin; using std::string;  bool checkEmptyString(const char *s)   return strlen(s) == 0; >  int main()   string string1("This is a non-empty string");  string string2;   checkEmptyString(string1.data()) ?  cout  <"[ERROR] string is empty!"  <endl :  cout  <"string value: "      checkEmptyString(string2.data()) ?  cout  <"[ERROR] string is empty!"  <endl :  cout  <"string value: "      return EXIT_SUCCESS; > 
string value: This is a non-empty string [ERROR] string is empty! 

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article — C++ String

Источник

Оцените статью