构造字符串
#include <iostream>
#include <cstdio>
using namespace std;
//构造字符串
int main() {
//solution 1
string name="dfasf";
const char *name1="dfdas";
string s2(name);
cout<<s2<<endl;
//dfasf
string s21(name1);
cout<<s21;
//dfdas
string a123(4,'a');
cout<<a123;
//aaaa
//solution 2
return 0;
}
字符串赋值
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
//字符串赋值
int main() {
//operator assign
string s1;
s1='a';
string s2;
s2= s1;
cout<<s2<<endl;
s2="dsafs";
//function solution;
s2.assign(s1);
cout<<s2<<endl;
s2.assign("dfads",2);
cout<<s2<<endl;
s2.assign(5,'l');
cout<<s2<<endl;
string s3(s2,4);
cout<<s3;
// string s4(4,s2)
// grammar false;
/*
a
a
df
lllll
l
*/
return 0;
}
字符串的追加
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
//字符串赋值
int main() {
string s2;
s2.assign(5,'l');
cout<<s2<<endl;
s2+="dafd";
s2+='a';
cout<<s2<<endl;
s2.append(s2,4,2);
cout<<s2<<endl;
//"F:\clion c++\code\cmake-build-debug\code.exe"
//lllll
//llllldafda
//llllldafdald
//
//Process finished with exit code 0
return 0;
}
字符串的查找和替换
//查找
//s2="lllllldafdald";
//find and replace
int pos = s2.find("ld");// find from left to right
//return value = -1, no "ld";
//return value = index of l ;
cout<<pos<<endl;//4
pos=s2.rfind("ld") ;//find from right to left;
cout<<pos<<endl;//10
//替换
//s2="lllllldafdald";
s2.replace(1,3,"liandashuaibi");
//从字符串的位置1起,3个字符替换为后面的字符串;
cout<<s2<<endl;
//lliandashuaibildafdald;
字符串之间的比较
string s3(s2,4,2);
cout<<s3<<endl;//s3=nd;
cout<<s3.compare(s2)<<endl;//1
cout<<s2.compare(s2)<<endl;//0
cout<<s2.compare(s3)<<endl;//-1
字符串访问字符
cout<<s2.at(2)<<endl;
cout<<s2[2];
字符串删除插入元素
s2.insert(1,"#$!1");
cout<<s2<<endl;
s2.erase(2,3);
cout<<s2<<endl;
/*
il#$!1liandashuaibildafdald
l#liandashuaibildafdald*/