这是自己写的 可能有点粗劣 欢迎大家提出补充,返回中文的字符串列表 跟英文的。
/// <summary>
/// 根据中英文混搭的情况 进行拆分
/// </summary>
/// <param name="str">输入的字符串比如 中文abc汉字库 返回 中文 汉字库 abc </param>
/// <param name="isEng">是否要返回英文</param>
/// <returns></returns>
public static List<string>SplitStr(string str, out List<string> engList, bool isEng = false)
{
List<string> strlist = new List<string>();
List<string> CnList = new List<string>();
List<string> EnList = new List<string>();
engList = new List<string>();
int strLength = 0;
StringBuilder stren = new StringBuilder();
StringBuilder strcn = new StringBuilder();
bool iscnup = true, iscn = false;
char[] Temp = str.ToCharArray();
for (int i = 0; i < Temp.Length; i++)
{
//判断中文或者其他
if (!CheckStringChinese(Temp[i])) //英文跟数字
{
stren.Append(Temp[i]);
iscn = false;
}
else
{
strcn.Append(Temp[i]);
iscn = true;
}
//开始添加到
if (i!=0&& iscn != iscnup && iscn == true)//中文字符到此为止
{
EnList.Add(stren.ToString());
stren.Clear();
}
else if (i != 0 && iscn != iscnup && iscn == false)
{
CnList.Add(strcn.ToString());
strcn.Clear();
}
if (i == Temp.Length-1 && iscn == true && strcn.Length>0)
{
CnList.Add(strcn.ToString());
}
else if (i == Temp.Length-1 && iscn == false && stren.Length > 0)
{
EnList.Add(stren.ToString());
}
iscnup = iscn;
}
engList = EnList;
strlist.AddRange(CnList);
if (isEng)
strlist.AddRange(EnList);
return strlist;
}
/// <summary>
/// 返回指定长度的list
/// </summary>
/// <param name="strstr">需要拆分的字符串</param>
/// <param name="lenth">每个拆分的长度默认是2</param>
/// <returns></returns>
public static List<string> GetStrList(string strstr, int lenth = 2)
{
//拆分搜索的字符长度 超过2位的 就自动分隔
int str1Count = 0;
//int strlConnt2 = Encoding.Unicode.GetByteCount(strstr);
List<string> strsql = new List<string>();
int strnum = 1;
str1Count = strstr.Length; //Encoding.Default.GetByteCount(strstr);
if (str1Count >= lenth + 1)
{
strnum = str1Count / lenth;
for (int k = 0; k < strnum; k++)
{
string str1 = "";
if (k == 0)
{
str1 = strstr.Substring(0, lenth);
}
else if (k == strnum - 1)
{
str1 = strstr.Substring(0 + (k * lenth), strstr.Length - k * lenth);
}
else
{
str1 = strstr.Substring(0 + (k * lenth), lenth);
}
strsql.Add(str1);
}
}
return strsql;
}
/// <summary>
/// 检查是不是汉子
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool CheckStringChinese(string text)
{
bool res = false;
for (int i = 0; i < text.Length; i++)
{
if ((int) text[i] > 127)
res = true;
else
{
res = false;
}
}
return true;
}
public static bool CheckStringChinese(char text)
{
bool res = text > 0x4e00 && text<0x9fbb;
return res;
}
浙公网安备 33010602011771号