Home > OS >  Qt - Replacing 1 character with multiple characters in a QString
Qt - Replacing 1 character with multiple characters in a QString

Time:08-09

I'm building a text converter that converts things to an exagerrated Scottish accent. Naturally, I need to turn all "u"s into "oo"s. And drop the g in any words that end with g. I'd like to know whether there's a method of replacing one character with more that one character in a QString.

Code I have so far, which converts one character to another character.

    void MainWindow::on_replaceU_clicked()

    QString example = "summarize";

    QString inputTextScottish = example.replace(QChar('u'), QChar('o'), Qt::CaseInsensitive);
    qDebug() << inputTextScottish; //Output: somarize

What I'm looking for, would probably do something like this.

example.replace(QChar('u'), QChar('oo'), Qt::CaseInsensitive); //Output: soomarize

Please let me know if more information is needed to solve this issue. This is based on the QString documentation.

CodePudding user response:

Short:

void MainWindow::on_replaceU_clicked()
    QString example = "summarize"; // Better: use QStringLiteral("summarize")

    QString inputTextScottish = example.replace(QChar('u'), QLatin1String("oo"), Qt::CaseInsensitive);
    qDebug() << inputTextScottish; // Output: soomarize

Longer

Why use QStringLiteral()?

Because it initializes the string at compile time, which is much faster than generating it at runtime

Why use QLatin1String()?

In short: it is much faster than QString or QStringLiteral (if there is an overload for QLatin1String()).

You can accept @perivesta's answer, because he was faster than me

  •  Tags:  
  • c qt
  • Related