首先明白一个概念,即string替换所有字符串,将"12212"这个字符串的所有"12"都替换成"21",结果是什么?
可以是22211,也可以是21221,有时候应用的场景不同,就会希望得到不同的结果,所以这两种答案都做了实现,代码如下:
[cpp] view plaincopy
#include
#include
using namespace std;
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;
}
int main()
{
cout << replace_all(string("12212"),"12","21") << endl;
cout << replace_all_distinct(string("12212"),"12","21") << endl;
}
/*
输出如下:
22211
21221
*/
OK,这样的话,任务就完成啦。
string给我们提供了很多的方法,但是每在使用的时候,就要费些周折。
场景1:
得到一个std::string full_path = “D:\program files\csdn”,但是我想得到”D:\program files\vagaa”这个路径。
这就需要字符串的替换
std::string full_path = "D:\\program files\\csdn"const size_t last_slash_idx1 = full_path .find_last_of("\\/");if (std::string::npos != last_slash_idx1)
{
full_path.erase(last_slash_idx1, std::string::npos);
}std::string my_path = full_path + "\\vagaa";1234567
这里用到了string的* find_last_of*方法,并使用了erase方法进行删除。
场景2:
得到一个std::string full_image_path = “D:\program files\csdn\vagaa.png”,但是我想根据这个路径得到文件的扩展名。
我们可以使用find_last_of+erase方法进行,还可以这么做:
std::string full_image_path = "D:\\program files\\csdn\\vagaa.png"std::string file_extension_name;size_t i = full_image_path .rfind('.', file_path.length());if (i != string::npos) {
file_extension_name = full_image_path .substr(i + 1, full_image_path .length() - i);}123456