Search code examples
c++qtqstringqtcore

QString replace only first occurrence


Is there simple way of replacing only first occurrence of some substring by other substring in QString? It can be at any position.


Solution

  • You could try this:

    QString str("this is a string"); // The initial string.
    QString subStr("is"); // String to replace.
    QString newStr("at"); // Replacement string.
    
    str.replace(str.indexOf(subStr), subStr.size(), newStr);
    

    Resulting string will be:

    that at a string