PDA

View Full Version : How to capitalize a string



cydside
18th July 2010, 15:16
Hi to all,
I can't believe that, it's missing a capitalizing function in Qt!!!
Does anyone suggest a quick way to do it?

Thanks in advance.

Lykurg
18th July 2010, 15:20
The doc it your friend. Use it! QString::toUpper()

cydside
18th July 2010, 17:21
The doc it your friend. Use it! QString::toUpper()

... for the first char and ::toLower() for the other chars. Thanks, who is the next?

Lykurg
18th July 2010, 17:32
Thanks, who is the next?
I hope you don't want to pull my leg. Where is the problem in combining that with normal c++ rules?

QString capitalize(const QString &str)
{
QString tmp = str;
// if you want to ensure all other letters are lowercase:
tmp = tmp.toLower();
tmp[0] = str[0].toUpper();
return tmp;
}

cydside
18th July 2010, 17:40
I hope you don't want to pull my leg. Where is the problem in combining that with normal c++ rules?

Sorry, I don't mean to hurt your feelings. I'm just looking for a smartest solution(if exist) used by someone else!

franz
18th July 2010, 20:43
... for the first char and ::toLower() for the other chars. Thanks, who is the next?

Uhm, the docs clearly state that TeXt turns into TEXT. If this isn't the case, either you have done something wrong or there's a bug in Qt. Since they have a QTestLib example built around this exact function, I am pretty sure you have done something wrong.

Edit: I really should pay a bit more attention. The question really wasn't clear enough but you noticed it yourself after lykurg's reply...

SixDegrees
18th July 2010, 21:01
There's no function to change the first character of a string to upper case because such a function makes little sense in many languages; it is a task specific mainly to Western languages and alphabets. In today's global, Unicode world the majority of readers would find such a function useless.

If that's all you need, however, however, myString[0].toUpper() will get you there. Feel free to define a macro, or a function, or simply hard-code the solution wherever it's needed.

clith
18th November 2010, 02:36
You can use QFont::setCapitalization(). I guess the rationale is that it's a rendering step.

Reid

marcvanriet
18th November 2010, 13:06
Hi,

I guess you want to capitalize all nouns in a sentence, as is common for titles in English.

Use the split method of QString, using a space as separator. This gives you a list of strings. toUpper() each first character of each string in the stringlist. Then concatenate all the strings back together, putting a space in between them.

You could add exceptions that the words 'and' and 'or' and such are not capitalized.

Best regards,
Marc

wysota
18th November 2010, 13:11
I usually do:

str = str.left(1).toUpper()+str.mid(1);