1. substr()
对字符串进行截取
string s = "0123456789";
string sub1 = s.substr(5); // 从下标为5开始一直到结尾:sub1 = "56789"
string sub2 = s.substr(5, 3); // 从下标为5开始截取长度为3位:sub2 = "567"
2. c_str()
返回一个指向正规
C
C
C 字符串的指针, 内容与本
s
t
r
i
n
g
string
string 串相同
注意这是一个临时指针
char str[20];
string s = "1234";
strcpy(str, s.c_str()); // 将 s拷贝到 str
printf("%s", s.c_str()); // 可以直接输出
3. replace()
用法一:
用
s
t
r
str
str 替换指定字符串从起始位置
p
o
s
pos
pos 开始,长度为
l
e
n
len
len 的字符
string& replace (size_t pos, size_t len, const string& str);
string s = "this@ is@ a test string!";
s = s.replace(s.find("@"), 1, ""); // 找到第一个@位置,替换长度为1的串为空
cout << s << endl; // "this is@ a test string!"
用法二:
用
s
t
r
str
str 替换 迭代器起始位置 到 结束位置 的字符
string& replace (const_iterator i1, const_iterator i2, const string& str);
string s = "this@ is@ a test string!";
s = s.replace(s.begin(), s.begin()+6, ""); // 用str替换从begin位置开始的6个字符
cout << s << endl; // "is@ a test string!"
用法三:
用
s
u
b
s
t
r
substr
substr 的指定子串(给定起始位置和长度)替换从指定位置上的字符串
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
string s = "this@ is@ a test string!";
string substr = "12345";
// 用substr的指定子串(从1位置数共3个字符)替换从0到5位置上的 s
s = s.replace(0, 5, substr, substr.find("1"), 3);
cout << s << endl; // "123 is@ a test sting!"
4. replace_all()
replace_all()
: 进行字符串替换,并循环换到没有为止
replace_all_distinct
: 进行字符串替换,只换一次
string& replace_all(string& str, const string& old_value, const string& new_value) {
while(true) {
string::size_type pos(0);
if( (pos=str.find(old_value))!=string::npos )
str.replace(pos, old_value.length(), new_value);
else break;
}
return str;
}
string& replace_all_distinct(string& str, const string& old_value, const string& new_value) {
for(string::size_type pos(0); pos!=string::npos; pos+=new_value.length()) {
if( (pos=str.find(old_value, pos))!=string::npos )
str.replace(pos, old_value.length(), new_value);
else break;
}
return str;
}
string str1 = "12212", str2 = "12212";
cout << replace_all(str1, "12", "21") << endl; // "22211"
cout << replace_all_distinct(str2, "12", "21") << endl; // "21221"