QString replace only first occurrence

user3136871 picture user3136871 · Jan 9, 2014 · Viewed 11k times · Source

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

Answer

vahancho picture vahancho · Jan 9, 2014

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