[Qt-interest] Converting first character of a char* from local charset

Nikos Chantziaras realnc at arcor.de
Fri May 27 16:21:15 CEST 2011


Is there some efficient way in Qt to convert the first character of a 
char* string from the local character set to Unicode?  Currently, the 
only way I was able to come up with is the following kludge:

     char* s;    // Contains characters in the system's charset.
     size_t len; // Length of 's'.
     QTextCodec* localCodec = QTextCodec::codecForLocale();
     // ...
     // Try to find how many bytes it takes to form a complete character.
     size_t i;
     for (i = 1; i <= len and localCodec->toUnicode(s, i).length() != 1;
          ++i)
         ;
     if (i > len) {
         // We couldn't convert.
         // ...
     } else {
         // The first character consists of the first 'i' bytes of 's'.
     }

I can imagine that the performance of this code ain't the best, since 
what it does is call QTextCodec::toUnicode() repeatedly, increasing the 
amount of characters each time, until it hits an amount of bytes that 
can be converted.

Is there a better way to achieve this?



More information about the Qt-interest-old mailing list