utf-8字符串中字符占用字节数

  1. 为了保护用户隐私,对一部分用户进行昵称首个字符替换为"*" ;
  2. 问题 :首个字符不确定是中文还是英文,英文可能占用一个字节,中文可能占用2-4字节,所以替换前需确定首个字符占用多少个字节
    默认按照utf8格式处理
点击查看代码
#include <iostream>

using namespace std;
//方法1 
void Utf8SubStr(string &name, string convert) {
    size_t i=0;
    size_t j=0;
    while (i<1 && j<name.length()) {
        unsigned char c = (unsigned char)name[j++];
        i += ((c & 0xc0) != 0x80);
    }

    while (j<name.length()) {
        unsigned char c = (unsigned char)name[j];
        if ((c & 0xc0) == 0x80) {
            j++;
        } else {
            break;
        }
    }
    name.replace(0, j, convert);
}
//方法2 自己根据utf8格式写的
// UTF-8是这么规定的:(x代表0或者1)
//
//只占一个字节的字符,8位字节第一位就是0
//0 X X X X X X X
//
//占用2个字节的字符,第一个字节的是以110开头,第二个字节以10开头
//1 1 0 X X X X X 1 0 X X X X X X
//
//占用3个字节的字符,第一个字节的是以1110开头,剩余字节都以10开头
//1 1 1 0 X X X X 1 0 X X X X X X 1 0 X X X X X X
//
//占用4个字节的字符,第一个字节的是以11110开头,剩余字节都以10开头
//1 1 1 1 0 X X X 1 0 X X X X X X 1 0 X X X X X X 1 0 X X X X X X
//https://zhuanlan.zhihu.com/p/363036851
int32_t FirstWordReplace(std::string & src,std::string replace = "*"){
    // 1. is chinese ?
    char *c = (char *)src.c_str();
    int first_word_len = 1;
    if ((*c & 0x80)==0x80){
        first_word_len = 1;
        if ((*c & 0xc0)==0xc0){
            first_word_len = 2;
            if ((*c & 0xe0) ==0xe0){
                first_word_len = 3;
                if ((*c & 0xf0) == 0xf0){
                    first_word_len = 4;
                    if ((*c & 0xf8)==0xf8){
                        first_word_len = 5;
                        if ((*c & 0xfc)==0xfc){
                            first_word_len = 6;
                        }
                    }
                }
            }
        }
    }
    // 2. replace
    cout<<first_word_len<<endl;
    src.replace(0, first_word_len, replace);
}
int main() {

    std::string test("龠编码aa");
    char * ptr =  (char *)test.c_str();
    printf("%x,%x,%x,%x,%x,%x,%x,%x\n",ptr[0],ptr[1],ptr[2],ptr[3],ptr[4],ptr[5],ptr[6],ptr[7]);
    cout<<test.c_str()<<endl;

    FirstWordReplace(test,"*");
    cout<<test.c_str()<<endl;
    printf("%x,%x,%x,%x,%x,%x,%x,%x\n",ptr[0],ptr[1],ptr[2],ptr[3],ptr[4],ptr[5],ptr[6],ptr[7]);

    return 0;
}

posted @ 2021-10-26 17:14  justdoitlittletomore  阅读(206)  评论(0)    收藏  举报