In Qt; what is the best method to capitalise the first letter of every word in a QString?

10.6k views Asked by At

I am thinking of regular expressions, but that is not exactly readable. There are also functions like s.toUpper() to consider, and probably other things as well.

So what is the best method for capitalising the first letter of words in a QString?

5

There are 5 answers

0
thuga On BEST ANSWER

Using this example as a reference, you can do something like this:

QString toCamelCase(const QString& s)
{
    QStringList parts = s.split(' ', QString::SkipEmptyParts);
    for (int i = 0; i < parts.size(); ++i)
        parts[i].replace(0, 1, parts[i][0].toUpper());

    return parts.join(" ");
}
2
Folco On

Incredible C++/Qt... You just want to get some chars ored with 0x20...

0
Thalia On

If the QString is placed in any item that uses QFont, you can use its setCapitalization property to change text to title case. Here is an example - my code is very happy to have discovered it.

QFont formatFont = m_formatNameEdit->font();
formatFont.setCapitalization(QFont::Capitalize);
m_formatNameEdit->setFont(formatFont);

Thanks to an answer from Qt Centre Thread: How to capitalize a string

0
darrenp On

There is an alternative way of doing this which iterates using references to the words and modifies the first character using a QChar reference instead:

QString capitalise_each_word(const QString& sentence)
{
  QStringList words = sentence.split(" ", Qt::SkipEmptyParts);
  for (QString& word : words)
    word.front() = word.front().toUpper();

  return words.join(" ");
}

Note that Qt::SkipEmptyParts is required here (as in the other answers to this question) since the first character of each word is assumed to exist when capitalising. This assumption will not hold with Qt::KeepEmptyParts (the default).

0
Rolling Panda On

Exactly the same, but written differently :

QString toCamelCase(const QString& s)
{
    QStringList cased;
        foreach (QString word, s.split(" ", QString::SkipEmptyParts))cased << word.at(0).toUpper() + word.mid(1);

    return cased.join(" ");
}

This uses more memory but is without pointer access (no brackets operator).