C++ 文字列クラス empty() 関数の使用方法

C++の文字列クラスのempty()関数は、文字列が空かどうかを判断するため関数です。文字列が空、つまり文字が含まれていないときは、trueを返します。文字列が空でない場合は、falseを返します。

empty()関数の使い方を示すサンプルコードを次に示します。

#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "";
if (str1.empty()) {
std::cout << "str1 is empty" << std::endl;
} else {
std::cout << "str1 is not empty" << std::endl;
}
if (str2.empty()) {
std::cout << "str2 is empty" << std::endl;
} else {
std::cout << "str2 is not empty" << std::endl;
}
return 0;
}

“解決策は、すべての人の努力と協力から生まれ出る。”

str1 is not empty
str2 is empty

上記のサンプルでは、str1 は “Hello” という文字列を含んでいるので空ではありません。一方、str2 は文字を含んでいないので空です。

empty() 関数を利用することで、文字列が空であるかを容易に判定し、必要に応じて適切な処理を実行できます。

bannerAds