c# - 你如何在 C# 中用 2 个字符计数进行字符串拆分?
问题描述
如果有要替换的字母、数字,我知道如何进行字符串拆分。
但是我怎么能在不替换任何现有字母、数字等的情况下string.Split()
进行 2char
计数?
例子:
string MAC = "00122345"
我希望该字符串输出:00:12:23:45
解决方案
您可以创建一个 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));
}
推荐阅读
- php - 将一列除以从子查询创建的另一列
- deep-learning - 如何在 Pytorch 中创建自定义损失函数
- c++ - C++ 中的动态安全二维交错数组
- c - 反向数组(带有 argc 和 argv)+ 如何打印它
- wikipedia - 如何使用 Wikipedia 的搜索选项“deepcat”?
- floating-point - 在 IEEE 754 中减去不同的数字总是非零?
- linux-device-driver - 将 Linux 驱动程序与设备树节点相关联
- c# - 为什么调试包括外部库代码
- kubernetes - 将 Kubernetes 和 Weave CNI 与同一子网中的多个集群一起使用
- php - 如何解码响应不仅仅是 JSON 字符串的 JSON 响应