QStringList怎麼分开中文英文
时间: 2023-07-02 11:05:41 浏览: 37
可以通过Unicode编码判断一个字符是否为中文字符,从而将中英文进行分开。以下是一个示例代码:
```
QStringList splitByChinese(QString str) {
QStringList result;
QString temp = "";
for(int i = 0; i < str.length(); i++) {
QChar c = str.at(i);
if(c.unicode() >= 0x4e00 && c.unicode() <= 0x9fa5) { // 中文字符
if(!temp.isEmpty()) {
result.append(temp);
temp = "";
}
temp.append(c);
result.append(temp);
temp = "";
} else { // 非中文字符
temp.append(c);
}
}
if(!temp.isEmpty()) {
result.append(temp);
}
return result;
}
```
该函数将会把传入的字符串按照中英文分开,返回一个QStringList对象。
相关问题
QStringList先排英文在排中文
可以使用QCollator进行字符串排序,QCollator可以根据语言的不同来进行排序。
以下是一个示例代码,可以实现将QStringList中的字符串按照英文在前,中文在后的顺序进行排序:
```cpp
#include <QtWidgets>
bool compare(const QString &s1, const QString &s2)
{
QCollator collator(QLocale(QLocale::English, QLocale::UnitedStates));
return collator.compare(s1, s2) < 0;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList list;
list << "apple" << "banana" << "中国" << "dog" << "cat" << "北京";
qSort(list.begin(), list.end(), compare);
foreach (const QString &str, list) {
qDebug() << str;
}
return app.exec();
}
```
在上面的代码中,我们定义了一个compare函数用于比较两个QString字符串的大小,QCollator使用了英语-美国语言环境进行排序,这样英文字符串就会排在中文字符串前面。然后我们使用qSort对QStringList进行排序,最后输出排序后的结果。
qstringlist显示中文
要在QStringList中显示中文,您需要确保使用正确的编码方式处理字符串。在Qt中,默认编码方式是UTF-8,可以正常显示中文字符。
以下是一个示例代码,演示如何在QStringList中显示中文:
```cpp
#include <QCoreApplication>
#include <QStringList>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QStringList stringList;
stringList << "中国" << "北京" << "上海";
foreach (const QString& str, stringList) {
qDebug() << str;
}
return a.exec();
}
```
上述代码创建了一个QStringList,并向其中添加了三个中文字符串。然后,使用foreach循环遍历QStringList并使用QDebug输出每个字符串。您可以在调试输出中看到正确的中文字符。
确保您的源代码文件也是以UTF-8编码方式保存的,以便正确处理包含中文的字符串。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)