c++stringqtqstring

Method to capitalise the first letter of every word in a QString


Using Qt, I need to capitalise the first letter of every word in a QString.

I thought of doing it using regular expressions, but that is not exactly readable. Maybe I can do it with a function like s.toUpper()?


Solution

  • 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(" ");
    }