首页 > 解决方案 > 你如何在 C# 中用 2 个字符计数进行字符串拆分?

问题描述

如果有要替换的字母、数字,我知道如何进行字符串拆分。

但是我怎么能在不替换任何现有字母、数字等的情况下string.Split()进行 2char计数?

例子:

string MAC = "00122345"

我希望该字符串输出:00:12:23:45

标签: c#stringsplit

解决方案


您可以创建一个 LINQ 扩展方法来为您提供IEnumerable<string>以下部分:

public static class Extensions
{
    public static IEnumerable<string> SplitNthParts(this string source, int partSize)
    {
        if (string.IsNullOrEmpty(source))
        {
            throw new ArgumentException("String cannot be null or empty.", nameof(source));
        }

        if (partSize < 1)
        {
            throw new ArgumentException("Part size has to be greater than zero.", nameof(partSize));
        }

        return Enumerable
            .Range(0, (source.Length + partSize - 1) / partSize)
            .Select(pos => source
                .Substring(pos * partSize, 
                    Math.Min(partSize, source.Length - pos * partSize)));
    }
}

用法:

var strings = new string[] { 
    "00122345", 
    "001223453" 
};

foreach (var str in strings)
{
    Console.WriteLine(string.Join(":", str.SplitNthParts(2)));
}
// 00:12:23:45
// 00:12:23:45:3

解释:

  • 用于Enumerable.Range获取对字符串进行切片的位置数。在这种情况下,它是length of the string + chunk size - 1, 因为我们需要获得足够大的范围来适应剩余的块大小。
  • Enumerable.Select切片的每个位置并startIndex使用String.Substring位置乘以 2 以每 2 个字符向下移动字符串。Math.Min如果字符串没有足够的字符来容纳另一个块,您将不得不使用来计算最小大小的剩余大小。您可以通过length of the string - current position * chunk size.
  • String.Join的最终结果":"

您还可以将 LINQ 查询替换yield为此处以提高较大字符串的性能,因为所有子字符串不会一次存储在内存中:

for (var pos = 0; pos < source.Length; pos += partSize)
{
    yield return source.Substring(pos, Math.Min(partSize, source.Length - pos));
}

推荐阅读