C++提供了一个处理字符串的标准类,它被定义在string里面,string类的对象可以通过C++的运算符进行操作,使用string是必须包括头文件string
string类对象可以用构造函数进行初始化,例如:
string s1("hello, world");
string s2="hello, world";
当然的话,也可以定义一个空字符
string类中重载了=、+、+=、比较符号、[]和输入输出符号
+ 号表示拼接两个字符串
[]的重载是字符串对象就可以作为字符数组来使用
除此之外, string中还定义了一组成员函数:
函数 | 作用 |
substr(start,len) | 取子串 |
capacity() | 字符串对象的容量 |
length() | 字符串的长度 |
find() | 查找字符串s在当前串中的位置 |
insert(pos, s) | 在当前字符串的位置pos前插入字符串s |
下面是这些函数的实际运用:
#include<iostream>
#include<string>
using namespace std;
int main() {
string str("Hello,world");
cout << "The length of str is :" << str.length() << endl;
cout << "The capacity of str is :" << str.capacity() << endl;
cout <<"The start position of world is : " <<str.find("world") << endl;
cout << "Get the string which begins with 1, and length is: " << str.substr(0, 5) << endl;
cout << "After insert \"your\" at 6, the new string is : "<< str.insert(6,"your ")<< endl;
return 0;
}
运行之后程序的输出为:
The length of str is :11
The capacity of str is :15
The start position of world is : 6
Get the string which begins with 1, and length is: Hello
After insert "your" at 6, the new string is : Hello,your world