關于 Qt MeeGo 中文字符串排序
本文講解的是關于 Qt MeeGo 中文字符串排序的實例,Qt類中的qSort()函數提供了對字符串的排序功能。要利用qSort為中文進行排序則需要我們提供一個針對中文比較規則的比較器。
Meego Touch Framework 中的MCollator實現了該功能。更準確地說是MCollator實現了所有國家語言的排序功能。
簡單的用法如下。
- MLocale loc; // 這里設置對應國家的語言和排序方法
- MCollator comp = loc.collator();
- QStringList stringList;
- //add contents to stringList
- qSort(stringList.begin(), stringList.end(), comp); // sorts the list
中文有按照拼音(pinyin)和筆畫(stroke)兩種排序方式.
所以我們構造MLocale的時候可以用
//根據拼音或筆畫選擇一種
- MLocale loc(“zh_CN@collation=pinyin”);
- MLocale loc(“zh_CN@collation=stroke”);
完整的代碼如下
- #include <QCoreApplication>
- #include <QObject>
- #include <MLocale>
- #include <MCollator>
- #include <QStringList>
- #include <QDebug>
- #include <QTextCodec>
- int main(int argc,char *argv[]){
- QCoreApplication app(argc,argv);
- //MLocale loc(locale_name);
- MLocale loc(“zh_CN@collation=pinyin”);
- MCollator mcomp = loc.collator();
- QTextCodec *tc=QTextCodec::codecForName(“utf8″);
- QTextCodec::setCodecForCStrings(tc);
- QStringList stringList;
- //stringList << “bb” << “da” << “aa” << “ab”;
- stringList<<”黨”<<”的”<<”政”<<”策”<<”亞”<<”克”<<”西”;
- qSort(stringList.begin(), stringList.end(), mcomp);
- qDebug()<<stringList;
- }
如果是按拼音排序輸出將是 (“策”, “黨”, “的”, “克”, “西”, “亞”, “政”).
而按筆畫排序輸出將是 (“西”, “克”,”的”,”政”, “黨”, “策”, “亞”).
需要注意的是編譯該代碼需要在你的工程文件.pro中加入CONFIG+=meegotouch。
小結:關于關于 Qt MeeGo 中文字符串排序的內容介紹完了,如果你還是不怎么清楚,多參考Qt類,會幫你解決更多的問題。希望本文對你有所幫助。