關(guān)于 Qt MeeGo 中文字符串排序
本文講解的是關(guān)于 Qt MeeGo 中文字符串排序的實(shí)例,Qt類中的qSort()函數(shù)提供了對(duì)字符串的排序功能。要利用qSort為中文進(jìn)行排序則需要我們提供一個(gè)針對(duì)中文比較規(guī)則的比較器。
Meego Touch Framework 中的MCollator實(shí)現(xiàn)了該功能。更準(zhǔn)確地說(shuō)是MCollator實(shí)現(xiàn)了所有國(guó)家語(yǔ)言的排序功能。
簡(jiǎn)單的用法如下。
- MLocale loc; // 這里設(shè)置對(duì)應(yīng)國(guó)家的語(yǔ)言和排序方法
- MCollator comp = loc.collator();
- QStringList stringList;
- //add contents to stringList
- qSort(stringList.begin(), stringList.end(), comp); // sorts the list
中文有按照拼音(pinyin)和筆畫(huà)(stroke)兩種排序方式.
所以我們構(gòu)造MLocale的時(shí)候可以用
//根據(jù)拼音或筆畫(huà)選擇一種
- 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;
- }
如果是按拼音排序輸出將是 (“策”, “黨”, “的”, “克”, “西”, “亞”, “政”).
而按筆畫(huà)排序輸出將是 (“西”, “克”,”的”,”政”, “黨”, “策”, “亞”).
需要注意的是編譯該代碼需要在你的工程文件.pro中加入CONFIG+=meegotouch。
小結(jié):關(guān)于關(guān)于 Qt MeeGo 中文字符串排序的內(nèi)容介紹完了,如果你還是不怎么清楚,多參考Qt類,會(huì)幫你解決更多的問(wèn)題。希望本文對(duì)你有所幫助。