按字符串长度变量将String拆分为较小的字符串

Bud*_*Joe 38 .net c# string algorithm

我想用特定的长度变量分解String.
它需要进行边界检查,以便在字符串的最后一部分不长于或长于字符串时不爆炸.寻找最简洁(但可以理解)的版本.

例:

string x = "AAABBBCC";
string[] arr = x.SplitByLength(3);
// arr[0] -> "AAA";
// arr[1] -> "BBB";
// arr[2] -> "CC"
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 64

你需要使用一个循环:

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
    for (int index = 0; index < str.Length; index += maxLength) {
        yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
    }
}
Run Code Online (Sandbox Code Playgroud)

替代方案:

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
    int index = 0;
    while(true) {
        if (index + maxLength >= str.Length) {
            yield return str.Substring(index);
            yield break;
        }
        yield return str.Substring(index, maxLength);
        index += maxLength;
    }
}
Run Code Online (Sandbox Code Playgroud)

2 选择:(对于那些谁也受不了while(true))

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
    int index = 0;
    while(index + maxLength < str.Length) {
        yield return str.Substring(index, maxLength);
        index += maxLength;
    }

    yield return str.Substring(index);
}
Run Code Online (Sandbox Code Playgroud)

  • @Mike:我认为第一个句子中没有主题的连续句子是不好的风格.(哦,快!) (4认同)
  • @Mike:我只是在开玩笑,geez.评论上的+1无论如何都是毫无意义的(不,我没有给自己+1).我只是觉得有点荒谬,因为你不喜欢他/她的*风格*."它回答了这个问题,而且效果很好,但是......我不喜欢那种风格,所以我会对它进行投票." (3认同)
  • 我想,伟大的思想是相似的!(或者更谦卑地说:伟大的思想和平庸的思想有时会有同样的想法?) (2认同)

Han*_*son 12

易于理解的版本:

string x = "AAABBBCC";
List<string> a = new List<string>();
for (int i = 0; i < x.Length; i += 3)
{
    if((i + 3) < x.Length)
        a.Add(x.Substring(i, 3));
    else
        a.Add(x.Substring(i));
}
Run Code Online (Sandbox Code Playgroud)

虽然最好3应该是一个很好的常量.

  • @JYelton:不,它仍然会进入循环并最终进入else语句. (3认同)

Mar*_*ers 6

它不是特别简洁,但我可能会使用这样的扩展方法:

public static IEnumerable<string> SplitByLength(this string s, int length)
{
    for (int i = 0; i < s.Length; i += length)
    {
        if (i + length <= s.Length)
        {
            yield return s.Substring(i, length);
        }
        else
        {
            yield return s.Substring(i);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我返回一个IEnumerable<string>,而不是一个数组.如果要将结果转换为数组,请使用ToArray:

string[] arr = x.SplitByLength(3).ToArray();
Run Code Online (Sandbox Code Playgroud)


Luk*_*sky 6

我的解决方案:

public static string[] SplitToChunks(this string source, int maxLength)
{
    return source
        .Where((x, i) => i % maxLength == 0)
        .Select(
            (x, i) => new string(source
                .Skip(i * maxLength)
                .Take(maxLength)
                .ToArray()))
        .ToArray();
}
Run Code Online (Sandbox Code Playgroud)

我实际上宁愿使用List<string>而不是string[].