下午闲着无聊, 帮同时解决字符对齐的问题
/// <summary>
/// 根据字符集,在字节级别分割为等长字符串数组
/// create by lz 2017-11-24
/// </summary>
/// <param name="strcnt"></param>
/// <param name="lenByteCount">注意这是字节长度</param>
/// <returns></returns>
private static string[] SubStrToSaLen(string strcnt, int lenByteCount)
{
List<string> lstStr = new List<string>();
string ret_str = strcnt;
if (ret_str.Length == 0)
{
return new string[] { ret_str };
}
byte[] byteArray = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strcnt);//.GetBytes(str);
if (byteArray.Length < lenByteCount)
return new string[] { strcnt };
int orgMod = (byteArray.Length / lenByteCount);
int lenCod = byteArray.Length % lenByteCount; //余数
if (lenCod > 0)
{
List<byte> lstbyte = new List<byte>();
lstbyte.AddRange(byteArray);
for (int i = lstbyte.Count; i < (orgMod + 1) * lenByteCount; i++)
{
lstbyte.Add(32);//用空格填充成整倍数
}
byteArray = lstbyte.ToArray();
}
int lenmod = byteArray.Length / lenByteCount; //整倍数
int start = 0;
int nstart = 0;
for (int i = 1; i <= lenmod; i++)
{
start = nstart;
byte[] ba = new byte[lenByteCount];
int sublen = lenByteCount;
int nCount = 0;
int eCount = 0;
for (int j = 0; j < lenByteCount; j++)
{
ba[j] = byteArray[start + j];
if (ba[j] > 127)
nCount++;//是汉字就统计数量
else
eCount++;
}
if (nCount % 2 != 0 && eCount % 2 != 0) //如果是奇数,就有半个汉字,丢失最后一个字节,
{
sublen = sublen - 1;
}
nstart = start + sublen;//设置下一个字符开始位置
ret_str = System.Text.Encoding.GetEncoding("GB2312").GetString(byteArray, start, sublen);
byte[] arbyte = System.Text.Encoding.GetEncoding("GB2312").GetBytes(ret_str);
if (arbyte.Length < lenByteCount)
{
List<byte> lsttmp = new List<byte>();
lsttmp.AddRange(arbyte);
lsttmp.Add(32);
ret_str = System.Text.Encoding.GetEncoding("GB2312").GetString(lsttmp.ToArray());
}
lstStr.Add(ret_str);
}
return lstStr.ToArray();
}