EasyString类(切分utf8编码的string) 您所在的位置:网站首页 税收分类编码大类 EasyString类(切分utf8编码的string)

EasyString类(切分utf8编码的string)

2023-06-30 17:48| 来源: 网络整理| 查看: 265

背景

QString用多了之后真心觉得std::string太原始。刚好有个切分utf8字符串的需求,所以简单封装了一个字符串类。

EasyString类

easyString.h

#ifndef EASYSTRING_H #define EASYSTRING_H #include #include class EasyString { public: EasyString(const std::string &str); const std::string &at(int); int size() const { return m_size; } private: std::vector m_strVct; int m_size; }; #endif // ! EASYSTRING_H

easyString.cpp

#include "easyString.h" int utf8TextLen(const char &c) { int num = 0; #if 1 for (int i = 0; i < 4; i++) { if (c&(0x80 >> i)) num++; else break; } #else switch (c & 0xE0) { case 0x80: return 1; case 0xC0: return 2; case 0xE0: return 3; default: break; } #endif // 0 return num; } c EasyString::EasyString(const std::string & str) { int sz = str.size(); for (int i = 0; i < sz;) { int num = utf8TextLen(str.at(i)); if (num == 0) { num++; } m_strVct.push_back(str.substr(i, num)); i += num; } m_size = m_strVct.size(); } const std::string &EasyString::at(int index) { return m_strVct.at(index); } 说明

EasyString类主要功能是将utf8编码的std::string切分,使得能够统计字符数(通过size函数)并能获取到各字符内容(通过at函数)。

核心函数为utf8TextLen函数,计算当前字符占几个字节,从而进行切分。其中使用了两种计算方式,性能上并没有太大区别。

目前EasyString只是一个简单的类,提供的功能也很有限,后续有需要时继续完善。

调用 EasyString eStr(u8"一二三四五"); auto size = eStr.size(); for (int i = 0; i < size; i++) { const string &newstr = eStr.at(i); } 注意

目前只支持utf8编码的字符串。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有