出现的一些函数
- s3.insert(7, “&Teacher”);//向串s3的7下标处插入串"&Teacher"
- s3.replace(2,4,“ar”);//利用replace函数将从string串s3的2下标开始的长度为4的字串替换为ar s1
- s1 = s3.substr(6, 7);//利用substr函数取出串s3的从6下标开始的长度为7的子串并赋值给s1串
- int pos = s3.find(s1);//在串s3中查找s1串是否存在,若存在则返回s1串的第一个子符在s3中的下标
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1;//定义空串s1
string s2="Student";//定义串s2初值为Student
string s3 = s2;//定义串s3初值为s2的值
string s4(8, 'A');//定义串s4初值为由8个A组成的串AAAAAAAA
cin >> s1;//读入sl的值,遇到空格回车Tab健停止
//若要读入带空格的串,用getline(cin,sl);替换该行
cout << s1 << endl << s2 << endl << s3 << endl << s4 << endl;
s4 = s1;//对string类型串变量s4赋值,右边可以是一个string串、c风格的串或者一个字符
cout << "s4=" << s4 << "length is:" << s4.length( ) << endl;
//string串名,length()用于求其串长
s2 = s3 + ' ' + s4;//+号实现串联结,左边为一个string类的串
//右边可以是一个string串、c风格的字符串或一个char字符
cout << "s2=" << s2 << endl;//输出结果为s2=Student Zhu
s3.insert(7, "&Teacher");//向串s3的7下标处插入串"&Teacher"
cout << "s3=" << s3 << endl;//输出结果s3=Student&Teacher
s3.replace(2,4,"ar");//利用replace函数将从string串s3的2下标开始的长度为4的字串替换为ar
cout << "s3=" << s3 << endl;//输出结果为s3=Start&Teacher
s1 = s3.substr(6, 7);//利用substr函数取出串s3的从6下标开始的长度为7的子串并赋值给s1串
cout << "s1=" << s2 << endl;//输出结果为s1=Teacher
int pos = s3.find(s1);//在串s3中查找s1串是否存在,若存在则返回s1串的第一个子符在s3中的下标
cout << "pos=" << pos << endl;//
s3.erase(5, 8);//删除串s3的从5下标开始的长度为8的子串
cout << "s3=" << s3 << endl;//
bool f = s1 > s4;//关系运算符可用于比较string串的大小
cout << f << " " << boolalpha << f << endl;//
return 0;
}
源码来自
人民邮电出版社《面向对象程序设计及C++》