工作中碰到甲方提供文件某字符串字段被截断,遗留半个中文字符串导致获取后出现乱码,只能写个方法做下判断过滤。
char* RetTruncate(char* strSrc, int nMaxLen)
{
if (strSrc == NULL || nMaxLen == 0) {
return NULL;
}
int index = 0;
int len = strlen(strSrc);
while(index < nMaxLen) {
if(strSrc[index] < 0) {
index += 2;
} else {
index += 1;
}
}
if(index > nMaxLen) {
strSrc[nMaxLen - 1]='\0';
} else if(len > nMaxLen) {
strSrc[nMaxLen] = '\0';
}
}
public final String readString(int size, boolean bTruncate) throws IOException {
byte [] b = new byte[size];
int n =read(b);
if (n < 0)
throw new EOFException();
if(bTruncate) RetTruncate(b, size);
return new String(b,"gbk").trim();
}
public void RetTruncate(byte[] value, int len)
{
int index = 0;
while(index < len) {
if( value[index] < 0 ) {
index += 2;
} else {
index += 1;
}
}
if(index > len) {
value[len-1]='\0';
} else if(value.length > len) {
value[len] = '\0';
}
}