2012-06-04 78 views
1

我想text=s-o-m-e=text喜欢的replaceAll替换字符(字符串,开始,结束, '_', ' - ')

替换字符串text=s_o_m_e=text我有一个起始和结束索引:

std::string str("text=s_o_m_e=text"); 

std::string::size_type start = str.find("text="), end; 

if (start != std::string::npos) { 
    end = str.find("=", start); 

    if (end != std::string::npos) { 
     //... 
    } 
} 

所以,我正在寻找这样的功能:

replaceAll(string, start, end, '_', '-'); 

UP:

谢谢,Blastfurnace

+1

[此问题]的完全重复(http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string)。 –

回答

10

那里有一个<algorithm>功能。

std::replace(str.begin(), str.end(), '_', '-'); 
+0

更多thx!所以,我的解决方案:'std :: replace(str.begin()+ start,str.end()+ end,'_',' - ');' – Duglas

+4

@Duglas:你不想引用过去的字符串的结尾。因为你正在使用偏移量,所以我想你需要'std :: replace(str.begin()+ start,str.begin()+ end,'_',' - ');' – Blastfurnace

+0

使用std :: replace,old_string和new_string必须具有相同的长度。即std :: replace(my_str.begin(),my_str.end(),“旧字符串”,“不能碰这个”);在模板参数推理中失败,即“模板参数推导/替换失败;注意:参数'const_Tp'('char [11]'和'char [17]')的推导冲突类型” – bitek

5

使用std::replaceHere是更多细节。

+1

+1,很好的参考。 – Blastfurnace

+0

-1,不好的答案:展示如何使用它的小片段会使它好多了。 –

+0

+1,很好的答案:需要学习使用文档。 –

相关问题