C++で文字列が空かどうかを判断します
この投稿では、C++で文字列が空かどうかを判断する方法について説明します。
1.使用する string::empty
関数
C++ で文字列が空かどうかを判断する 1 つの方法は、 empty()
からの機能 std::string
クラス。この関数は、文字列に文字が含まれているかどうかを示すブール値を返します。たとえば、文字列が空かどうかを確認したい場合は、次のようなことができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = ""; if (s.empty()) { std::cout << "String is empty" << std::endl; } else { std::cout << "String is not empty" << std::endl; } return 0; } |
出力:
String is empty
The empty()
この関数は、文字列に文字が含まれているかどうかのみをチェックします。文字列に空白文字のみが含まれているかどうかはチェックされません。たとえば、次の文字列 " "
は空とみなされません empty()
目に見える文字が含まれていない場合でも、機能します。
2.使用する string::size
関数
C++ で文字列が空かどうかを判断するもう 1 つの方法は、 size()
文字列クラスの関数。これらのメソッドは、文字列内のバイト数を示す整数値を返します。を使用するには、 size()
関数で文字列が空かどうかを判断するには、戻り値をゼロと比較する必要があります。例えば:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = ""; if (s.size() == 0) { std::cout << "String is empty" << std::endl; } else { std::cout << "String is not empty" << std::endl; } return 0; } |
出力:
String is empty
3.使用する string::length
関数
The string::length
関数はのエイリアスです string::size
関数。文字列の長さをバイト単位で返します。空の文字列の長さは 0 です。次のように使用できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = ""; if (s.length() == 0) { std::cout << "String is empty" << std::endl; } else { std::cout << "String is not empty" << std::endl; } return 0; } |
出力:
String is empty
これで、C++で文字列が空かどうかを判断できます。