Q: c# 中有没有什么封装方法实现每隔两个字符分割字符串?
如:str = "AB80CD90";
输出:分割后的数组 {“AB”,“80”,“CD”,“90”}
string[] result=new string[str.Length/2];
for(int i=0;i<str.Length/2;i++)
{
result[i]=str.SubString(2*i,2);
}
//return result;
Regex.Matches(Str, $"\\w{2}").Cast<Match>().Select(s => s.Value)
你这是分隔M1卡ID吧,这样就可以了,不用太麻烦。
回复的一楼是不错的答案,但是 如果是字符串长度是单数那么你就取不到最后的 所以我改了下
string str = "123456789";
string[] result;
string ee = "";
if (str.Length % 2 != 0)
{
result = new string[str.Length / 2 + 1];
ee = str.Substring(str.Length - 1, 1);
}
else
{
result = new string[str.Length / 2];
}
for (int i = 0; i < str.Length / 2; i++)
{
result[i] = str.Substring(2 * i, 2);
}
if (!string.IsNullOrEmpty(ee))
{
result[result.Length-1] = ee;
}