根据数组的块长度拆分字符串

  • 本文关键字:拆分 字符串 数组 c#
  • 更新时间 :
  • 英文 :


此代码适用于固定大小:

public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) 
throw new ArgumentException();
if (chunkLength < 1) 
throw new ArgumentException();

for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;

yield return str.Substring(i, chunkLength);
}
}

此代码用于根据固定的chunkLength拆分字符串,例如3。

但是我需要根据chunksize的数组修改拆分字符串,例如6,3。

我稍微修改了一下

public static IEnumerable<string> SplitBy(this string str, int[] chunkLengths)
{
if (String.IsNullOrEmpty(str)) 
throw new ArgumentException();
if (chunkLengths.Length < 1) 
throw new ArgumentException();

foreach (int chunkLength in chunkLengths)
{
int i = 0;
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
i += chunkLength;
}
}

用法:

通话正常:

var result = "bobjoecat".SplitBy(3);      // bob, joe, cat

这就是我需要的:

var result = "bobjoecat".SplitBy([6,3]);   // bobjoe, cat

忽略任何其他概念性或非概念性问题,并故意忽略任何容错和边界检查

给定

public static IEnumerable<string> SplitBy(this string str, int[] chunkLengths)
{
var offset = 0;
foreach (var chunkLength in chunkLengths)
{
yield return str.Substring(offset, chunkLength);
offset += chunkLength;
}
}

使用

var result = "bobjoecat".SplitBy(new []{6, 3});
foreach (var item in result)
Console.WriteLine(item);

bobjoe
cat

注意,我本来可以在Demo这里的注释中回答这个问题的,然而,仓鼠在。net小提琴似乎已经死亡的时刻