@RabbitHu
2017-09-19T15:33:43.000000Z
字数 2006
阅读 7054
笔记
将字符串2赋值给字符串1:
1. 字符串1 = 字符串2;
2. 字符串1.assign(字符串2);
string s1 = "I'm ";
string s2;
s2 = "1234Juruo1234";
s1.assign(s2);
cout << s1;
//输出结果:1234Juruo1234
将字符串2从第m个字符开始的n个字符赋值给字符串1:
字符串1.assign(字符串2, m, n);
string s1 = "I'm ";
string s2 = "1234Juruo1234";
s1.assign(s2, 4, 5);
cout << s1;
//输出结果:Juruo
返回字符串长度:
1. 字符串1.length();
2. 字符串1.size();
string s1 = "1234Juruo1234";
cout << s1.length() << endl;
cout << s1.size() <<endl;
/*
输出结果:
13
13
*/
">", "<", "==", ">=", "<="均可以用于字符串比较。
string PPAP[] = {"I", "have", "a", "pen", "an", "apple", "um", "apple-pen"};
sort(PPAP, PPAP + 8);
for(int i = 0; i < 8; i++){
cout << PPAP[i] << endl;
}
/*
输出结果:
I
a
an
apple
apple-pen
have
pen
um
*/
在字符串1中从第m个字符开始查找字符串2,返回第一次出现的首字母位置,失败时返回-1:
字符串1.find(字符串2, m);
string s1 = "ggabcdabcgggabcdefg";
string s2 = "gg";
int pos = -1;
while(1){
pos = s1.find(s2, pos+1);
if(pos == -1) break;
cout << pos << ' ';
}
//输出结果:0 9 10
在字符串1中从第m个字符开始从后向前查找字符串2,返回第一次出现的首字母位置,失败时返回-1:
字符串1.rfind(字符串2, m);
string s1 = "ggabcdabcgggabcdefg";
string s2 = "gg";
int pos = s1.length();
while(pos > 0){
pos = s1.rfind(s2, pos-1);
if(pos < 0) break;
cout << pos << ' ';
}
//输出结果:10 9 0;
将字符串2接到字符串1尾部:
1. 字符串1.append(字符串2); //字符不可
2. 字符串1 += 字符串2; //字符亦可
string s1 = "I'm ";
string s2 = "Juruo";
s1.append(s2);
// 或 s1 += s2;
cout << s1;
//输出结果:I'm Juruo
将字符串2从第m个字符开始的n个字符接到字符串1尾部:
字符串1.append(字符串2, m, n);
string s1 = "I'm ";
string s2 = "1234Juruo1234";
s1.append(s2, 4, 5);
cout << s1;
//输出结果:I'm Juruo
字符串1.swap(字符串2);
string s1 = "I'm ";
string s2 = "Juruo";
s1.swap(s2);
cout << s1 << endl;
//输出结果:Juruo
返回字符串1从第m个字符开始的n个字符所组成的子串:
字符串1.substr(m, n);
string s1 = "I'm ";
string s2 = "1234Juruo1234";
s1 = s2.substr(4, 5);
cout << s1 << endl;
//输出结果:Juruo
在字符串1中删除从m开始的n个字符,然后在m处插入串s2
字符串1.replace(m, n, s2);
string s1 = "I'm Juruo";
string s2 = "Juruo";
string s3 = "Dalao";
int pos = s1.find(s2);
s1.replace(pos, s2.length(), s3);
cout << s1;
//输出结果:I'm Dalao
在字符串1的第m个字符处插入字符串2:
字符串1.insert(m, 字符串2);
string s1 = "I'm Juruo";
string s2 = "not ";
s1.insert(s1.find("Juruo", 0), s2 );
cout << s1 << endl;
//输出结果:I'm not Juruo
从字符串1的第m个字符开始,删除n个字符:
字符串1.erase(m, n);
string s1 = "I'm not Dalao";
s1.erase(s1.find("not"), 4);
cout << s1 << endl;
作者:胡小兔 //←这个网站经常崩溃
批评指正敬请联系:yuanxiaodidl@163.com
打赏一根胡萝卜: