GBK漢字截斷

背景

    在搜索引擎自動生成摘要時經常要限制字符串的長度,超過MAXLEN的摘要截斷,並在串尾加"......"。假設文本串已經由utf-8或者其它編碼轉爲GBK編碼,這裏給出個簡單實現(但不是最好的方法)。

    漢字的GBK編碼把一個漢字用兩個字節來表示,首字節第一位爲1,所以直接取其值爲負值。此處,轉換爲unsigned char後取其值,首字節對應0x81-0xFE(即129~254),尾字節對應去掉(0x7F)的0x40-0xFE(即64~126和128~254)。

代碼:

/**
 * is_gbk.c
 * 必須保證漢字已經是GBK編碼
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int MAXLEN = 10;
int main(int argc, char* argv[])
{
	char str[] = "你好hello世界world";
	int nlen = strlen(str);
	if (nlen <= MAXLEN)
	{
		exit(0);
	}
	size_t i;
	for (i = 0; i < nlen; ++i)
	{
		if (i >= MAXLEN)
		{
			str[i] = '\0';
			strcat(str, "...\0");
			break;
		}
		if (str[i] >= 0) // 非漢字
		{
			continue;
		}
		unsigned char ch1 = str[i];
		unsigned char ch2 = str[i + 1];
		if ((ch1 >= 129 && ch2 <= 254) &&
				(ch2 >=64 && ch2<=126 || ch2 >= 128 && ch2 <= 254))
		{
			// gbk漢字
			i++;
		}
	}
	printf("%s\n", str);
	exit(0);
}
運行結果:

你好hello世...

備註:如果直接strncpy(newstr, str, sizeof(char) * 10)的運行結果爲

你好hello�...

亂碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章