62,046
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 重复多次匹配分割字符串
/// </summary>
/// <param name="s">被分割的字符串</param>
/// <param name="separator">分隔符</param>
/// <param name="count">分隔符的重复匹配次数,也就是分隔符匹配多少次时进行分割,当count为1时就相当于.NET自带的Split函数</param>
/// <returns>返回生成的数组</returns>
static string[] SplitString(string s, char separator, int count)
{
List<string> list = new List<string>();
int last = 0;//截取字符串的起始索引
int next = s.IndexOf(separator, last);//截取字符串的终止索引
while (next <= s.Length && next - last > 0)
{
string temp = s.Substring(last, next - last);
if (temp[0] == separator)
{
temp = temp.Substring(1);
}
list.Add(temp);
last = next;
//循环匹配count次
for (int i = 1; i <= count; i++)
{
if (next >= 0&& next <s.Length)
{
next = s.IndexOf(separator, next + 1);
}
else//当next==-1时
{
next = s.Length ;
}
}
}
return list.ToArray();
}
string[] s= SplitString("1,1,1,1,2,2,2,2", ',', 2);
foreach (var item in s)
{
Console.WriteLine(item);
}
String.IndexOf(
char value,
int startIndex
)
string str = "1,1,1,1,2,2,2,2";
int Num = str.Split(',').Length / 4;
for (int i =0; i <Num; i++)
{
string splitstr = null;
splitstr = str.Substring(i*8, 7);
Console.WriteLine(splitstr);
splitstr = null;
}
Console.WriteLine(str.Substring(Num * 8, str.Length-Num*8));
using System.Text.RegularExpressions;
Regex regex = new Regex(
@"\d,\d,\d,\d",
RegexOptions.IgnoreCase
);