引入

使用string类型必须首先包含string头文件,同时作为标准库的一部分,string定义在命名空间std中。

1
2
#include <string>
using namespace std;

定义与初始化

分为直接初始化拷贝初始化顾名思义

1
2
3
4
string s1;
string s2 = s1;
string s3 = "hiya";
string s4(10, 'c'); //10个c

读取位置数量的string对象

1
2
3
4
5
6
7
int main()
{
string word;
while (cin >> word)
cout << word << endl;
return 0;
}

使用getline读取一整行

getline()函数的参数是一个输入流和一个string对象,函数从给定的输入流中读入内容,直到遇到换行符为止(注意换行符也被读进来),然后把所读的内容存入到那个string对象中去(注意不存换行符)。

1
2
3
4
5
6
7
int main()
{
string line;
while (getline(cin, line))
cout << line << endl;
return 0;
}

string的empty和size操作

1
2
line.empty();   // 判断line是否为空
line.size(); // 返回line的长度

size_type类型

size()函数返回的不是int而是string::size_type类型的值。

在C++11新标准中允许编译器通过auto或者decltype来推断变量的类型

1
auto len = line.size();     // len的类型是string::size_type

由于size函数返回的是一个无符号整型数,因此切记,如果在表达式中混用了带符号数和无符号数将可能产生意想不到的结果。

比较string对象

原则:

  1. 如果两个string对象的长度不同,而且较短string对象的每个字符都与较长string对象对应位置上的字符相同,就说较短string对象小于较长string对象。
  2. 如果两个string对象在某些对应的位置上不一-致, 则string对象比较的结果其实是string对象中第- - 对相异字符比较的结果。

字面值与string对象相加

当把string对象和字符字面值及字符串字面值混在一条语句中使用时,必须确保每个加法运算符(+)的两侧的运算对象至少有一个是string

1
2
3
4
5
string s1 = "hello"; s2 = "world"
string s4 = s1 + ", "; //正确
string s5 = "hello" + ", "; //错误
string s6 = s1 + ", " + "world"; //正确:等价于(s1 + ", ") + "world"
string s7 = "Hello" + ", " + s2; //错误:不能将字面值直接相加

字符串字面值与string是不同的类型。

处理string对象中的字符

使用cctype头文件

1
2
3
4
5
6
7
8
9
10
11
12
13
isalnum(c)      // 当c是字母或数字时为真
isalpha(c) // 当c是字母时为真
iscntrl(c) // 当c是控制字符时为真
isdigit(c) // 当c是数字时为真
isgraph(c) // 当c不是空格但可打印时为真
islower(c) // 当c是小写字母时为真
isprint(c) // 当c是可打印字符时为真(即c是空格或c具有可视形式)
ispunct(c) // 当c是标点符号时为真(即c不是控制字符、数字、字母、可打印空白的一种)
isspace(C) // 当c是空白时为真(即c是空格、横向制表符、纵向制表符、回车符、换行符、进纸符中的一种)
isupper(c) // 当c是大写字母时为真
isxdigit(c) // 当c是十六进制数字时为真
tolower(c) // 如果c是大写字母,输出对应的小写字母:否则原样输出c
toupper(c) // 如果c是小写字母,输出对应的大写字母:否则原样输出c

处理每个字符

1
2
for (declaration : expression)
statement

如果要想改变string对象中字符的值,必须把循环变量定义成引用类型。

1
2
3
4
string s("hello World!!!");
for (auto &c : s)
c = toupper(c);
cout << s << endl;

只处理一部分字符

要想访问string对象中的单个字符有两种方式:

  • 使用下标
  • 使用迭代器

使用下标

将首字母大写

1
2
3
string s("some string");
if (!s.empty())
s[0] = toupper(s[0]);

把第一个词改为大写

1
2
3
for (decltype(s.size()) index = 0;
index != s.size() && !isspace(s[index]); ++index)
s[index] = toupper(s[index]);

&&:逻辑与运算符