21xrx.com
2024-09-19 09:09:58 Thursday
登录
文章检索 我的文章 写文章
C++如何判断一个字符串是否为空?
2023-07-13 22:48:29 深夜i     --     --
C++ 判断 字符串

C++中判断一个字符串是否为空可以采用以下几种方法。

方法一:使用empty()函数

C++中,可以使用std::string类的empty()函数来判断一个字符串是否为空。如果字符串为空,则返回true;否则,返回false。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = ""; // 空串

  if(str.empty())

  

    cout << "字符串为空" << endl;

  

  else

  

    cout << "字符串不为空" << endl;

  

  return 0;

}

方法二:使用size()函数

另一种方法是使用std::string类的size()函数,它返回字符串的长度,当长度为0时,即为空串。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = ""; // 空串

  if(str.size() == 0)

  

    cout << "字符串为空" << endl;

  

  else

  

    cout << "字符串不为空" << endl;

  

  return 0;

}

方法三:直接判断

还可以直接判断字符串的第一个字符是否为'\0',如果是,则字符串为空;否则,字符串不为空。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = ""; // 空串

  if(str[0] == '\0')

  

    cout << "字符串为空" << endl;

  

  else

  

    cout << "字符串不为空" << endl;

  

  return 0;

}

综上,采用任一种方法都可以判断一个字符串是否为空,建议使用empty()函数或size()函数,因为它们更加直观易懂。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复