C++字符串是否为空

C++字符串是否为空教程

C++ 中,我们需要判断 string 字符串是否为空,有五种方法,即使用 empty 函数、使用 length 函数、使用 size 函数、与空字符串 相等比较 以及与空字符 compare 对比。

其中,使用 empty 函数,判断字符串是否为空的效率是最高的,因此,推荐使用此方法。

C++字符串empty详解

语法

s.empty();

参数

参数 描述
s 要判断为空的字符串 s。

返回值

如果为空,则返回 true,否则,返回 false。

C++字符串length判断为空详解

语法

s.length() == 0;

参数

参数 描述
s 要判断为空的字符串 s。

返回值

如果为空,则返回 true,否则,返回 false。

说明

我们使用字符串的 length 函数,获取字符串的长度,并与 0 比较,如果相等,则字符串为空。

C++字符串size判断为空详解

语法

s.size() == 0;

参数

参数 描述
s 要判断为空的字符串 s。

返回值

如果为空,则返回 true,否则,返回 false。

说明

我们使用字符串的 size 函数,获取字符串的长度,并与 0 比较,如果相等,则字符串为空。

C++字符串相等比较判断为空详解

语法

s == "";

参数

参数 描述
s 要判断为空的字符串 s。

返回值

如果为空,则返回 true,否则,返回 false。

说明

我们可以直接使用 == 号,与空字符串比较。

C++字符串compare判断为空详解

语法

s.compare("");

参数

参数 描述
s 要判断为空的字符串 s。

返回值

如果为空,则返回 true,否则,返回 false。

说明

我们可以直接使用 compare 函数,与空字符串比较。

案例

字符串是否为空判断

使用五种方法,实现判断字符串是否为空

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string s = ""; bool sIsEmpty1 = s.empty(); bool sIsEmpty2 = s.length() == 0; bool sIsEmpty3 = s.size() == 0; bool sIsEmpty4 = s == ""; int sIsEmpty5 = s.compare(""); cout << "sIsEmpty1 = " << sIsEmpty1 << ", sIsEmpty2 = " << sIsEmpty2 << endl; cout << "sIsEmpty3 = " << sIsEmpty3 << ", sIsEmpty4 = " << sIsEmpty4 << endl; cout << "sIsEmpty5 = " << sIsEmpty5 << endl; }

程序运行后,控制台输出如下:

13_C字符串string是否为空.png

我们可以直接使用字符串的 empty 函数,判断字符串是否为空,接着,我们使用了 length 函数,获取了字符串的长度,并与 0 对比,如果相等,那么就是空字符串。

我们也可以使用字符串的 size 函数,获取其长度,并与 0 对比,如果相等,那么就是空字符串,同时,我们也可以直接将字符串与空进行相等比较,如果相等,则是空字符串。

最后,我们使用了 compare 函数,实现了将字符串与空字符串比较,这里需要注意的是,其返回的是 int 类型的值,如果相等则返回 0。

字符串不为空判断

使用五种方法,实现判断字符串是否不为空

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string s = "HaiCoder"; bool sIsEmpty1 = s.empty(); bool sIsEmpty2 = s.length() == 0; bool sIsEmpty3 = s.size() == 0; bool sIsEmpty4 = s == ""; int sIsEmpty5 = s.compare(""); cout << "sIsEmpty1 = " << sIsEmpty1 << ", sIsEmpty2 = " << sIsEmpty2 << endl; cout << "sIsEmpty3 = " << sIsEmpty3 << ", sIsEmpty4 = " << sIsEmpty4 << endl; cout << "sIsEmpty5 = " << sIsEmpty5 << endl; }

程序运行后,控制台输出如下:

14_C字符串string是否为空.png

我们首先,定义了一个非空字符串,接着,我们使用了五种方法,来实现对字符串的空判断。

C++字符串是否为空总结

在 C++ 中,我们需要判断 string 字符串是否为空,有五种方法其中,使用 empty 函数,判断字符串是否为空的效率是最高的,因此,推荐使用此方法。