string类
【string初始化】
示例:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1="hello world"; //把字符串赋给当前字符串s1
cout<<s1<<endl;
string s2=s1; //把字符串s1赋给当前字符串s2
cout<<s2<<endl;
string s3("yesterday once more"); //把字符串赋给当前字符串s3
cout<<s3<<endl;
string s4(s3); //把字符串s3赋给当前字符串s4
cout<<s4<<endl;
string s5(s1,6,5); //把字符串s1中从下标为6的位置开始的5个字符赋给当前字符串
cout<<s5<<endl;
string s6(10,'i'); //用10个字符i赋值给当前字符串
cout<<s6<<endl;
string s8(s3.begin(),&s3[3]); //把首地址和下标为3之间的部分赋给字符串
cout<<s8<<endl;
return 0;
}
/*
运行结果:
hello world
hello world
yesterday once more
yesterday once more
world
iiiiiiiiii
yes
*/
【string字符操作】
示例:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1="hello";
string s2(" world");
s1+=s2; //将s2连接到s1后面
cout<<s1<<endl;
string s3=s1+s2; //将s1和s2连接到s3后面
cout<<s3<<endl;
char str[]="wo"; //将字符串str连接到s3后面
s3+=str;
cout<<s3<<endl;
char ch='a';
s3+=ch; //将字符a连接到s3后面
cout<<s3<<endl;
cout<<s3[1]<<endl; //输出下标为3的元素
if(s1>s2) //比较字符串
cout<<'>'<<endl;
s3=s1;
if(s1==s3)
cout<<'='<<endl;
return 0;
}
/*
运行结果:
hello world
hello world world
hello world worldwo
hello world worldwoa
e
>
=
*/
【string成员函数】
find | 从字符串查找字符或字符串,返回第一次找到的位置 |
示例:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
string s1="hello";
string s2(" world");
string s3="hello";
sort(s1.begin(),s1.end()); //对字符串排序
cout<<s1<<endl; //ehllo
cout<<s1.size()<<' '<<s1.length()<<endl;//输出字符串实际长度//5 5
cout<<s1.max_size()<<endl; //输出可容纳的最大字符个数//4294967293
s1.resize(2); //改变实际长度
cout<<s1<<endl; //eh
cout<<s1.size()<<' '<<s1.length()<<endl;//输出字符串实际长度//2 2
cout<<s1.empty()<<endl; //判断是否为空//0
s1.erase(); //删除字符串
cout<<s1.empty()<<endl; //判断是否为空//1
s1.assign(s2); //重新赋值
cout<<s1<<endl; // world
s1.erase(0,1); //删除从0开始的1个字符
cout<<s1<<endl; //world
cout<<s1.at(1)<<endl; //访问下标为1的元素//o
s1.insert(0,s2); //在0的位置插入字符串s2
cout<<s1<<endl; // worldworld
s1.insert(0,'h'); //在0的位置插入字符h
cout<<s1<<endl; //h worldworld
s1.swap(s3); //s1与s3交换
cout<<s1<<endl; //hello
s1.replace(0,3,"abc"); //从0的位置开始,替换字符串abc的前3个字符
cout<<s1<<endl; //abclo
char s5[100];
s1.copy(s5,2,0); //在s1中从0开始的位置拷贝2个字符到s5中
s5[2]=0;
cout<<s5<<endl; //ab
string s4="aaaaabbcd";
int pos;
pos=s4.find("ab"); //在s1中查找子串ab,返回下标,否则返回-1
cout<<pos<<endl; //4
pos=s4.find("ko",0); //从字符串0号位置查找子串
cout<<pos<<endl; //-1
pos=s4.find('b',0); //在s1中查找字符b,返回下标,否则返回-1
cout<<pos<<endl; //5
string str="aa";
for(pos=0;(pos=s4.find(str,pos))!=-1;pos+=str.length())//查找str在s4中每次出现的位置
cout<<pos<<' '; //0 2
cout<<endl;
string s6;
s6=s4.substr(0,2); //产生从0开始长度为2的子字符串
cout<<s6<<endl; //aa
cout<<s4.compare(s4)<<endl; //比较字符串相等返回0,大于返回正数,小于返回负数//0
cout<<s4.compare(str)<<endl; //1
cout<<s4.compare(4,1,str)<<endl; //从s4的下标为4的位置开始比较长度为1的字符串//-1
cout<<s4.compare(3,1,str,0,1)<<endl; //从s4的下标为3的位置开始比较长度为1的字符串,与str从下标为0的位置比较//0
return 0;
}