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?
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(" ");
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With