一、概述
标准库类型 string
用来表示可变长的字符串序列,使用它需要包含 string
头文件。
作为标准库的一部分,它被定义在 std
命名空间中,使用前需要加上以下代码:
1 2 |
#include <string> using std::string; |
## string/string.h/cstring 三者的区别
string: STL 中的 string 类型的头文件。
string.h: C 语言中的一些字符串函数的头文件,例如 strcpy(), strcmp() 等等。
cstring: C++中为了区分 C 语言头文件的头文件表示法,去掉 C 语言头文件中的.h 尾巴并在首部加上一个字符 c,实际上等价于 C 语言中的 string.h 。
二、 string 对象的基本用法
2.1 string 对象的初始化
string 的初始化有多种方法:
1 2 3 4 5 |
string s1; // 默认初始化,s1 是一个空字符串 string s2 = s1; // 拷贝初始化 string s3 = "heiheihei"; // 通过字面值字符串赋值 string s4("hello"); // 直接初始化 string s5(10, "c"); // 给 s4 赋值位 10 个 c |
其中 s1-s4
都是常见的赋值操作,只有 s5
不同,它表示使用 10 个 c
来初始化 string 对象
。
2.2 string 的运算
相对 C++中的另一种字符串 char*
来说,string 对象
要灵活得多。
因为在面对字符串运算时,char*
显得有些无能为力,而 string 对象
却十分简单。
s1+s2
: 字符串相加s1==s2
: 判断相等,只有两个字符串长度相等并且每一位上的元素也相等时才相等<, <=, >, >=
: 根据字典顺序对两个字符串进行比较
1 2 3 4 5 6 7 8 9 10 11 |
string s1 = "Hello", s2 = "Wrold"; string s3 = "hello", s4 = "world"; // 字符串相加 string s5 = s1 + s2; cout << s1 << s2 << endl; // HelloWorld cout << s5 << endl; // HelloWorld // 字符串比较 cout << (s1 < s3 ? s1 : s3) << endl; // Hello |
三、 string 对象的其他操作
3.1 读写输入输出流
string 对象
能直接从标准的 iostream
库进行读写操作,在读写的过程中会忽略开头的空白,到下一个空白为止。
1 2 3 4 5 6 7 |
string word; while (cin >> word){ if (word == "exit"){ break; } cout << word << endl; } |
运行结果:
1 2 3 4 5 6 7 8 |
> hello hello > ok ok > hello world hello world > exit |
代码每次只能读取一个字符串,对于一个包含有空格的行,cin
是无法一次读取到 string 对象
的。
如果需要读取空白字符可以使用 getline()
函数:
1 2 3 4 5 6 |
while (getline(cin, word)){ if (word.empty()){ break; } cout << word << endl; } |
getline
会以
作为输入字符串的结束字符来读入,但是在放到
string 对象
时会把它丢掉。
1 2 3 4 5 6 |
> hello hello > hello world hello world > abc def ghi abc def ghi |
3.1 判断大小及是否为空
string 提供了 size()
方法和 empty()
方法用来获取字符串的长度以及判断字符串是否为空。
string::size()
方法返回一个 string::size_type
类型,它是一个无符号的足够存放下任何 string 对象
大小的整形值。
并且和 char*
字符串不同的是:string 对象并不是以结尾,因此不能通过
来作为
string 对象
结束的依据。
1 2 3 4 5 6 7 8 9 |
string s1; string s2 = "HelloWorld"; cout << s1.empty() << " " << s2.empty() << endl; cout << s1.size() << " " << s2.size() << endl; |
输出:
1 2 3 4 5 6 |
> g++ string.cpp -o app > ./app 1 0 0 10 |
四、 string 的遍历
4.1 通过下标遍历
string 对象
也有和数组一样的下标访问方式:s[1], s[2], ...
,它的下标范围是 [0,size())
。
1 2 3 4 5 6 |
string s = "helloworld"; unsigned int i = 0; for (; i < s.size(); i++){ cout << s[i]; } cout << endl; |
1 2 3 |
> g++ string.cpp -o app > ./app helloworld |
4.2 使用范围 for 循环遍历
C++ 11
提供了一种新的 for 循环方式可以用来遍历 string 对象
:
1 2 3 4 5 |
string s("helloword"); for(auto &c : s){ c = toupper(c); // 需要引入头文件 cctype } cout << s << endl; |
1 2 3 |
> g++ string.cpp -o app > ./app HELLOWORD |
评论