1. 程式人生 > 其它 >utf-8字串中字元佔用位元組數

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;
}