Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 570
user3136871 Avatar asked Jan 09 '14 15:01

user3136871


2 Answers

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

like image 79
vahancho Avatar answered Oct 22 '22 01:10

vahancho


There is no convenience method for the operation you wish to have. However, you can use the following two methods to build your custom operation:

int QString::indexOf(const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns the index position of the first occurrence of the string str in this string, searching forward from index position from. Returns -1 if str is not found.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

and

QString & QString::replace(int position, int n, const QString & after)

Replaces n characters beginning at index position with the string after and returns a reference to this string.

Note: If the specified position index is within the string, but position + n goes outside the strings range, then n will be adjusted to stop at the end of the string.

Now, putting all that into practice, you could write something as follows:

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    QString initialString = QLatin1String("foo bar baz");
    QString fooString = QLatin1String("foo");
    initialString.replace(initialString.indexOf(fooString),
                          fooString.size(), QLatin1String("stuff"));
    qDebug() << initialString;
    return 0;
}

main.pro

TEMPLATE = app                                         
TARGET = main                                              
QT = core                                              
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

"stuff bar baz" 
like image 30
lpapp Avatar answered Oct 22 '22 00:10

lpapp