如何替換字符串中出現的所有字符?中的其他字符替換所有出現的字符的有效方法是什么?std::string?
3 回答
眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
charactersubstrings
std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;}std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;
豆子數
xjxxgtXty
赫赫加斯蒂
編輯:
voidstr
代碼:
static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to){
// Same inner code...
// No return statement}- 3 回答
- 0 關注
- 1252 瀏覽
添加回答
舉報
0/150
提交
取消
