一、概述
标准库类型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 |
评论