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�...

乱码。

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