字符串:遍历、加密、统计、匹配
定义方式构造字符串
#include<bits/stdc++.h>
using namespace std;
int main(){
string s0="Initial String";
string s1;
string s2(s0);
string s3(s0,8,3);
string s4("A character sequence");
string s5("A character sequence",12);//其中12位
string s6(10,'x');//十个重复的数字
cout<<"s1 "<<s1<<endl;
cout<<"s2 "<<s2<<endl;
cout<<"s3 "<<s3<<endl;
cout<<"s4 "<<s4<<endl;
cout<<"s5 "<<s5<<endl;
cout<<"s6 "<<s6<<endl;
}
字符串操作
#include<bits/stdc++.h>
using namespace std;
int main(){
string str ="hello world";
for(int i=0;i<str.size();i++){
cout<<str[i];
}
string str1="to be a question";
string str2="that is a";
string str3="or not world";
string str4;
//插入
str4.insert(0,str1);
cout<<"str4 "<<str4<<endl;
str4.insert(6,str3,0,7);
cout<<"str4 "<<str4<<endl;
str4.insert(13,"to be");
cout<<"str4 "<<str4<<endl;
str4.insert(19,str2);
cout<<"str4 "<<str4<<endl;
str4.erase(19);//从19下标之后都不要了
str4.erase(0,9);//从0开始删除9个
cout<<"str4: "<<str4<<endl;
str4.clear();
cout<<"str4: "<<str4<<endl;
return 0;
}
字符串运算
#include<bits/stdc++.h>
using namespace std;
int main(){
//字符串拼接
string str1="to be";
string str2="not to be";
string str3="that is a question";
string str=str1+';';
cout <<str<<endl;
str =str+str2+';';
cout <<str<<endl;
str +=str3;
cout <<str<<endl;
str1="ab";
str2="abc";
str3="bcc";
cout<<(str1<=str2)<<endl;
cout<<(str2!=str3)<<endl;
cout<<(str3<str1)<<endl;
}
字符串函数
#include<bits/stdc++.h>
using namespace std;
int main(){
string str1="hello world,end world";
int length=str1.size();
cout<<length<<endl;
int position1 =str1.find("world");//从第0开始找
int position2 =str2.find("world",10);//从第10开始找
cout<<position1<<" "<<position2<<endl;
//找字符用''
position1=str1.find('a');//找不到返回-1
cout<<position1<<endl;
//返回字符串子串函数
string str2=str1.substr(13);//从这个开始到结尾
string str3=str1.substr(13,3);//只要其中一段 第二个参数是返回几个字符
cout<<str2<<endl<<str3<<endl;
return 0;
}
什么时候我能养成写博客的习惯!