简体   繁体   English

如何在QString中检测到非ASCII字符?

[英]How can non-ASCII characters be detected in a QString?

I want to detect if the user has inputted a non-ASCII (otherwise incorrectly known as Unicode) character (for example, り) in a file save dialog box. 我想检测用户是否在文件保存对话框中输入了非ASCII(否则错误地称为Unicode)字符(例如,り)。 As I am using Qt, any non-ASCII characters are properly saved in a QString, but I can't figure out how to determine if any of the characters in that string are non-ASCII before converting the string to ASCII. 当我使用Qt时,任何非ASCII字符都正确保存在QString中,但我无法弄清楚在将字符串转换为ASCII之前如何确定该字符串中的任何字符是否为非ASCII。 That character above ends up getting written to the filesystem as ã‚Š . 上面的那个字符最终被写入文件系统ã‚Š

最简单的方法是检查每个charachter的代码( QChar :: unicode() )是否低于128,如果你需要纯7位ASCII

There is no such a built-in feature in my understanding. 我的理解中没有这样的内置功能。

About 1-2 years ago, I was proposing an isAscii() method for QString/QChar to wrap the low-level Unix isacii() and the corresponding Windows function, but it was rejected. 大约1 - 2年前,我提出了一个用于QString / QChar的isAscii()方法来包装低级Unix isacii()和相应的Windows函数,但它被拒绝了。 You could have written then something like this: 你可以写下这样的东西:

bool isUnicode = !myString.at(3).isAcii();

I still think this would be a handy feature if you can convince the maintainer. 如果你能说服维护者,我仍然认为这将是一个方便的功能。 :-) :-)

Other than that, you would need to check against the ascii boundary yourself, I am afraid. 除此之外,你恐怕需要自己检查ascii边界。 You can do this yourself as follows: 您可以自己完成以下操作:

bool isUnicode = myChar.unicode() > 127; 

See the documentation for details: 有关详细信息,请参阅文档

ushort QChar::unicode () const ushort QChar :: unicode()const

This is an overloaded function. 这是一个过载功能。

要在没有循环的情况下以紧凑方式编写它,您可以使用正则表达式:

bool containsNonASCII = myString.contains(QRegularExpression(QStringLiteral("[^\\x{0000}-\\x{007F}]")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM