C++ String替换&分割指定字符串
1、C++ String替换指定字符串
C++的string对象提供了replace方法来实现字符串的替换,本文实现对于将字符串中某个字符串全部替换的功能。
string& replace_all(string& str, const string& strold, const string& strvalue)
{
while (true) {
string::size_type pos(0);
if ((pos = str.find(strold)) != string::npos) //"string::npos"means find failed
str.replace(pos, strold.length(), strvalue);
else break;
}
std::cout << str<<std::endl;
return str;
}
2、String分割指定字符串
根据指定的标识进行分割字符串。
void Split(const string& src, const string& separator,vector<std::string>& dest)
{
string str = src;
string substring;
string::size_type start = 0, index=0;
dest.clear();
index = str.find_first_of(separator, start);
do
{
if (index != string::npos)
{
substring = str.substr(start, index - start);//从start截取长度为index-start的字符串
dest.push_back(substring);
start = index + separator.size();//重新找起点 index+分割字符串长度为起点
index = str.find(separator, start);//从开始到下一个分隔符处
if (start == string::npos) break;
}
} while (index != string::npos);
substring = str.substr(start); //最后一部分字符串(下标为start开始一直到结尾)
dest.push_back(substring);
}
spolt函数参数说名:参数1:要分割的字符串;参数2:作为分隔符的字符;参数3:存放分割后的字符串的vector向量。
3、string中find_first_of和find方法说明
区别:
find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的***任何字符***,则就会查找成功,而find则不同;
下面例子在自己跑一边 就能理解他俩不同之处了。
int strFind()
{
string str1("Hi,every one! I am heat_nan from ZZULI. one");
string str2("heat_nan");
int k = str1.find(str2);
cout << "The position of 'heat_nan' is " << k << endl;
int k1 = str1.find("one");
cout << "The postion of the first 'one' is " << k1 << endl;
int k2 = str1.find("one of", k1 + 1, 3);//从str1中的k+1个字符开始查找"one of"的前三个字符
cout << "The postion of the second 'one' is " << k2 << endl;
int k3 = str1.find_first_of("aeiou");//here k3=1
while (k3 != string::npos) //"string::npos"means find failed
{
str1[k3] = '*';
k3 = str1.find_first_of("aeiou", k3 + 1);
}
cout << str1 << endl;
return 0;
}