wordtopinyin.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #ifndef WORDTOPINYIN_H
  2. #define WORDTOPINYIN_H
  3. #include <QTextCodec>
  4. class WordToPinyin
  5. {
  6. public:
  7. static bool In( quint16 start, quint16 end, quint16 code)
  8. {
  9. return (code>=start && code<=end) ? true : false;
  10. }
  11. static char convert(quint16 n)
  12. {
  13. if (In(0xB0A1,0xB0C4,n)) return 'a';
  14. if (In(0XB0C5,0XB2C0,n)) return 'b';
  15. if (In(0xB2C1,0xB4ED,n)) return 'c';
  16. if (In(0xB4EE,0xB6E9,n)) return 'd';
  17. if (In(0xB6EA,0xB7A0,n)) return 'e';
  18. if (In(0xB7A1,0xB8c0,n)) return 'f';
  19. if (In(0xB8C1,0xB9FD,n)) return 'g';
  20. if (In(0xB9FE,0xBBF6,n)) return 'h';
  21. if (In(0xBBF7,0xBFA4,n)) return 'j';
  22. if (In(0xBFA5,0xC0AA,n)) return 'k';
  23. if (In(0xC0AB,0xC2E7,n)) return 'l';
  24. if (In(0xC2E8,0xC4C2,n)) return 'm';
  25. if (In(0xC4C3,0xC5B5,n)) return 'n';
  26. if (In(0xC5B6,0xC5BD,n)) return 'o';
  27. if (In(0xC5BE,0xC6D9,n)) return 'p';
  28. if (In(0xC6DA,0xC8BA,n)) return 'q';
  29. if (In(0xC8BB,0xC8F5,n)) return 'r';
  30. if (In(0xC8F6,0xCBF9,n)) return 's';
  31. if (In(0xCBFA,0xCDD9,n)) return 't';
  32. if (In(0xCDDA,0xCEF3,n)) return 'w';
  33. if (In(0xCEF4,0xD1B8,n)) return 'x';
  34. if (In(0xD1B9,0xD4D0,n)) return 'y';
  35. if (In(0xD4D1,0xD7F9,n)) return 'z';
  36. return '\0';
  37. }
  38. //获取首字母
  39. static QString firstPinyin(const QString &string)
  40. {
  41. QTextCodec *codec4gbk = QTextCodec::codecForName("GBK"); //获取qt提供的gbk的解码器
  42. QByteArray buf = codec4gbk->fromUnicode( string ); //qt用的unicode,专程gbk
  43. int size = buf.size();
  44. quint16 *array = new quint16[size+1]{0};
  45. QString alphbats;
  46. for( int i = 0, j = 0; i < size; i++, j++ )
  47. {
  48. if( (quint8)buf[i] < 0x80 ) //gbk的第一个字节都大于0x81,所以小于0x80的都是符号,字母,数字etc
  49. {
  50. alphbats.append(QString("%1").arg(buf[i]));
  51. continue;
  52. }
  53. array[j] = (((quint8)buf[i]) << 8) + (quint8)buf[i+1]; //计算gbk编码
  54. i++;
  55. alphbats.append( convert( array[j] ) ); //相当于查表,用gbk编码得到首拼音字母
  56. }
  57. delete [] array;
  58. return alphbats;
  59. }
  60. };
  61. #endif