项目中偶尔要用到替换指定字符的功能,因为不常用每次一用到的就去官方文档看,总得花点儿时间感觉不是那么好用,自己想了个办法,可能性能不是最好的但我感觉应该是最直观明了的;以下是实现:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
std::string str("123 232 434 65r"); //替换所有空格
std::vector<char> vec_str = std::vector<char>(std::make_move_iterator(str.begin()), std::make_move_iterator(str.end()));//move 如果不用 make_move_iterator 则是copy
std::for_each(vec_str.begin(), vec_str.end(), [](char& c){
if (c == ' ')c = '_';
});
str = std::string(std::make_move_iterator(vec_str.begin()), std::make_move_iterator(vec_str.end()));
std::cout << str << std::endl;
return 0;
}