您好非ASCII字符转换为&#XXX; (其中XXX是一个数字):
/***************************************************************************//*!
* @brief Encode all non ASCII characters into ...;
* @param[in] src Text to analyze
* @param[in,opt] force Force the characters "list" to be converted.
* @return ASCII text compatible.
*
* @note Original code: http://www.qtforum.org/article/3891/text-encoding.html
*
* @warning Do not forget to use QString::fromUtf8()
*/
QString encodeEntities(const QString& src, const QString& force=QString())
{
QString tmp(src);
uint len = tmp.length();
uint i = 0;
while(i
{
if(tmp[i].unicode() > 128 || force.contains(tmp[i])){
QString rp = ""+QString::number(tmp[i].unicode())+";";
tmp.replace(i,1,rp);
len += rp.length()-1;
i += rp.length();
}else{
++i;
}
}
return tmp;
}
/***************************************************************************//*!
* @brief Allows decode ...; into UNICODE (utf8) character.
* @param[in] src Text to analyze
* @return UNICODE (utf8) text.
*
* @note Do not forget to include QRegExp
*/
QString decodeEntities(const QString& src)
{
QString ret(src);
QRegExp re("([0-9]+);");
re.setMinimal(true);
int pos = 0;
while((pos = re.indexIn(src, pos)) != -1)
{
ret = ret.replace(re.cap(0), QChar(re.cap(1).toInt(0,10)));
pos += re.matchedLength();
}
return ret;
}
基本用法:
qDebug() << encodeEntities(QString::fromUtf8("éà@<>hello the world €"),QString("<>"));
// Will print: éà@<>hello the world €
qDebug() << decodeEntities("aßéplopéàçê€");
// Will print: hello world