每第 N 个字符/数字拆分一个字符串/数字? [英] Splitting a string / number every Nth Character / Number?
问题描述
我需要将一个数字分成偶数部分,例如:
I need to split a number into even parts for example:
32427237 需要变成 324 272 37
103092501 需要变成 103 092 501
32427237 needs to become 324 272 37
103092501 needs to become 103 092 501
如何拆分它并处理奇数情况,例如导致这些部分的拆分,例如123 456 789 0?
How does one go about splitting it and handling odd number situations such as a split resulting in these parts e.g. 123 456 789 0?
推荐答案
如果你必须在代码的很多地方这样做,你可以创建一个花哨的扩展方法:
If you have to do that in many places in your code you can create a fancy extension method:
static class StringExtensions {
public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));
for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}
}
然后您可以像这样使用它:
You can then use it like this:
var parts = "32427237".SplitInParts(3);
Console.WriteLine(String.Join(" ", parts));
根据需要输出为 324 272 37
.
当您将字符串拆分为多个部分时,即使原始字符串中已经存在这些子字符串,也会分配新的字符串.通常,您不应该太担心这些分配,但是使用现代 C# 您可以通过稍微更改扩展方法以使用跨度"来避免这种情况:
When you split the string into parts new strings are allocated even though these substrings already exist in the original string. Normally, you shouldn't be too concerned about these allocations but using modern C# you can avoid this by altering the extension method slightly to use "spans":
public static IEnumerable<ReadOnlyMemory<char>> SplitInParts(this String s, Int32 partLength)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));
for (var i = 0; i < s.Length; i += partLength)
yield return s.AsMemory().Slice(i, Math.Min(partLength, s.Length - i));
}
返回类型更改为 public static IEnumerable
并且通过在未分配的源上调用 Slice
来创建子字符串.
The return type is changed to public static IEnumerable<ReadOnlyMemory<char>>
and the substrings are created by calling Slice
on the source which doesn't allocate.
请注意,如果您在某个时候必须将 ReadOnlyMemory
转换为 string
以在 API 中使用,则必须分配新的字符串.幸运的是,除了 string
之外,还有许多使用 ReadOnlyMemory
的 .NET Core API,因此可以避免分配.
Notice that if you at some point have to convert ReadOnlyMemory<char>
to string
for use in an API a new string has to be allocated. Fortunately, there exists many .NET Core APIs that uses ReadOnlyMemory<char>
in addition to string
so the allocation can be avoided.
这篇关于每第 N 个字符/数字拆分一个字符串/数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!