本文讲解的是关于 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类,会帮你解决更多的问题。希望本文对你有所帮助。