qt html转换成字符串,如何在QT中将实体字符(转义字符)转换为HTML?

您好非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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值