Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 387
Anon Avatar asked Dec 21 '16 00:12

Anon


2 Answers

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(" ");
}
like image 55
thuga Avatar answered Sep 23 '22 15:09

thuga


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).

like image 44
Rolling Panda Avatar answered Sep 23 '22 15:09

Rolling Panda