5 AĞUSTOS 2010, PERŞEMBE
Başka bir dize ile bir dize parçası değiştirin
C Olası başka bir dize ile bir dize parçası değiştirmektir. Temelde, bunu yapmak istiyorum
QString string("hello $name");
string.replace("$name", "Somename");
ama Standart C kütüphaneleri kullanmak istiyorum.
CEVAP
5 AĞUSTOS 2010, PERŞEMBE
Bir işlevi bir dize içinde bir dize (find
), ve bir işlevi yerine belirli bir aralık içinde bir dize ile bir dize (replace
), birleştirebilirsiniz o konuya etkisi.
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string string("hello $name");
replace(string, "$name", "Somename");
Yorum yanıt olarak, replaceAll
muhtemelen şöyle bir şey olurdu sanırım
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
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(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
Bunu Paylaş:
Nasıl bir dize Swift başka bir dize iç...
Nasıl dize bir normal ifade giriş için...
Nasıl bir dize Objective-C başka bir d...
Bir dize kontrol etmek için en hızlı y...
Check dize değil't başka bir dize...