在C++中提供了一个型的内建数据类型string,该数据类型可以替代C语言中char数组。需要使用string数据类型时则需要在程序中包含头文件string。
1.string类型的简单赋值
#include
<iostream>
#include
<string>
using
namespace
std;
int
main()
{
string s1;
//默认为空
string s2 =
"123456";
//直接字符串赋值,string类型的末尾没有'\0'
string s3 = s2;
//s2的值直接赋值给s3
string
s4(
10,
's');
//变量s4初始化为10个‘s’字符组成的字符串,也即“ssssssssss”。
cout<<
"s1 = "<<s1<<endl;
cout<<
"s2 = "<<s2<<endl;
cout<<
"s3 = "<<s3<<endl;
cout<<
"s4 = "<<s4<<endl;
return
0;
}
ubuntu下打印结果:

2.string长度
string s1 =
"123456";
cout<<s1.
length()<<endl;
//使用c_str转换为字符串
cout <<
"buf = "<<s1.
c_str()<<endl;
cout <<
"sizeof = "<<
sizeof(s1.
c_str())<<endl;
cout <<
"strlen = "<<
strlen(s1.
c_str())<<endl;
ubuntu运行结果:

3.string的输入输出
string s1;
cout<<
"in = ";
cin>>s1;
cout<<
"out = "<<s1<<endl;
ubuntu输出结果为:

注意:string输入不可以有空格,否则会出现数据输出不完整现象.

4.string类型字符串的拼接
//使用 + 和 += 进行拼接
string s1 =
"nihao";
string s2 =
"wo";
string s3 = s1 + s2;
s3 +=
"shi";
s3 +=
"shui";
cout<<
"s3 = "<<s3<<endl;
5.字符串修改
//字符串修改
string s1 =
"helwo";
s1[
3]=
'l';
cout<<
"s1 = "<<s1<<endl;
ubuntu打印结果为:

6.删除字符串erase
erase函数可以删除string类型变量中的一个子字符串。erase函数有两个参数,第一个参数是要删除的子字符串的起始下标,第二参数是要删除子字符串的长度,如果第二个参数不指名的话则是直接从第一个参数获取起始下标,然后一直删除至字符串结束。
//erase函数
string s1 =
"hello world";
s1.
erase(
5);
//获取前5个,删除到字符串介素
cout<<
"s1 = "<<s1<<endl;
string s2 =
"hello world";
s2.
erase(
5,
3);
//从起始下班5往后3个长度的全部删除
cout<<
"s2 = "<<s2<<endl;
ubuntu的打印结果为:

7.insert函数
函数insert可以在string字符串中指定的位置插入另一个字符串,该函数同样有两个参数,第一个参数表示插入位置,第二参数表示要插入的字符串,第二个参数既可以是string变量,又可以是C风格的字符串
//insert函数
string s1 =
"hllo";
s1.
insert(
1,
"e");
cout<<
"s1 = "<<s1<<endl;
//从下表1中增加e
8.replace函数
replace函数可以用一个指定的字符串来替换string类型变量中的一个子字符串,该函数有三个参数,第一个参数表示待替换的子字符串的其实下标,第二个参数表示待替换子字符串的长度,第三个参数表示要替换子字符串的字符串。第三个参数同样可以是string类型变量或C风格字符串。
//replace函数
string s1 =
"hello home";
s1.
replace(
6,
5,
"world");
cout<<
"s1 = "<<s1<<endl;
ubuntu上的打印结果为:

9.swap函数
swap函数可以用于将两个string 类型变量的值互换。
//swap函数
string s1 =
"hello";
string s2 =
"world";
s1.
swap(s2);
cout<<
"s1 = "<<s1<<endl;
cout<<
"s2 = "<<s2<<endl;
ubuntu上的打印结果为:

10.substr
函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。
//substr函数
string s1 =
"hello my home";
string s2 = s1.
substr(
6,
2);
cout<<
"s2 = "<<s2<<endl;
ubuntu上的打印结果为:

11.find函数
find函数可以在字符串中查找子字符串中出现的位置。该函数有两个参数,第一个参数是待查找的子字符串,第二个参数是表示开始查找的位置,如果第二个参数不指名的话则默认从0开始查找,也即从字符串首开始查找。
string s1 =
"hello world";
int index = s1.
find(
"world",
0);
cout<<index<<endl;
ubuntu上的打印结果是:

12.字符串的比较
“==”、 “!=”、 “<=”、 “>=”、 “<”和“>”操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。
此处不在举例.