SORU
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ş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • FPSRussia

    FPSRussia

    19 NİSAN 2010
  • Microsoft Help & Training Videos

    Microsoft He

    31 Mart 2009
  • TechSmartt

    TechSmartt

    29 Aralık 2010