每个第 N 个字符/数字拆分一个字符串/数字?

我需要把一个数字分成偶数部分,例如:

32427237需要变成32427237
103092501需要变成103092501

如何进行分割,并处理奇数情况,例如分割导致这些部分,例如1234567890?

112942 次浏览

One very simple way to do this (not the most efficient, but then not orders of magnitude slower than the most efficient).

    public static List<string> GetChunks(string value, int chunkSize)
{
List<string> triplets = new List<string>();
while (value.Length > chunkSize)
{
triplets.Add(value.Substring(0, chunkSize));
value = value.Substring(chunkSize);
}
if (value != "")
triplets.Add(value);
return triplets;
}

Heres an alternate

    public static List<string> GetChunkss(string value, int chunkSize)
{
List<string> triplets = new List<string>();
for(int i = 0; i < value.Length; i += chunkSize)
if(i + chunkSize > value.Length)
triplets.Add(value.Substring(i));
else
triplets.Add(value.Substring(i, chunkSize));


return triplets;
}

You could use a simple for loop to insert blanks at every n-th position:

string input = "12345678";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (i % 3 == 0)
sb.Append(' ');
sb.Append(input[i]);
}
string formatted = sb.ToString();

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));

The output is 324 272 37 as desired.

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));
}

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.

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.

This might be off topic as I don't know why you wish to format the numbers this way, so please just ignore this post if it's not relevant...

How an integer is shown differs across different cultures. You should do this in a local independent manner so it's easier to localize your changes at a later point.

int.ToString takes different parameters you can use to format for different cultures. The "N" parameter gives you a standard format for culture specific grouping.

steve x string formatting is also a great resource.

The splitting method:

public static IEnumerable<string> SplitInGroups(this string original, int size) {
var p = 0;
var l = original.Length;
while (l - p > size) {
yield return original.Substring(p, size);
p += size;
}
yield return original.Substring(p);
}

To join back as a string, delimited by spaces:

var joined = String.Join(" ", myNumber.SplitInGroups(3).ToArray());

Edit: I like Martin Liversage solution better :)

Edit 2: Fixed a bug.

Edit 3: Added code to join the string back.

I would do something like this, although I'm sure there are other ways. Should perform pretty well.

public static string Format(string number, int batchSize, string separator)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= number.Length / batchSize; i++)
{
if (i > 0) sb.Append(separator);
int currentIndex = i * batchSize;
sb.Append(number.Substring(currentIndex,
Math.Min(batchSize, number.Length - currentIndex)));
}
return sb.ToString();
}

I like this cause its cool, albeit not super efficient:

var n = 3;
var split = "12345678900"
.Select((c, i) => new { letter = c, group = i / n })
.GroupBy(l => l.group, l => l.letter)
.Select(g => string.Join("", g))
.ToList();

LINQ rules:

var input = "1234567890";
var partSize = 3;


var output = input.ToCharArray()
.BufferWithCount(partSize)
.Select(c => new String(c.ToArray()));

UPDATED:

string input = "1234567890";
double partSize = 3;
int k = 0;
var output = input
.ToLookup(c => Math.Floor(k++ / partSize))
.Select(e => new String(e.ToArray()));

Try this:

Regex.Split(num.toString(), "(?<=^(.{8})+)");

If you know that the whole string's length is exactly divisible by the part size, then use:

var whole = "32427237!";
var partSize = 3;
var parts = Enumerable.Range(0, whole.Length / partSize)
.Select(i => whole.Substring(i * partSize, partSize));

But if there's a possibility the whole string may have a fractional chunk at the end, you need to little more sophistication:

var whole = "32427237";
var partSize = 3;
var parts = Enumerable.Range(0, (whole.Length + partSize - 1) / partSize)
.Select(i => whole.Substring(i * partSize, Math.Min(whole.Length - i * partSize, partSize)));

In these examples, parts will be an IEnumerable, but you can add .ToArray() or .ToList() at the end in case you want a string[] or List<string> value.

This is half a decade late but:

int n = 3;
string originalString = "32427237";
string splitString = string.Join(string.Empty,originalString.Select((x, i) => i > 0 && i % n == 0 ? string.Format(" {0}", x) : x.ToString()));

A nice implementation using answers from other StackOverflow questions:

"32427237"
.AsChunks(3)
.Select(vc => new String(vc))
.ToCsv(" ");  // "324 272 37"


"103092501"
.AsChunks(3)
.Select(vc => new String(vc))
.ToCsv(" "); // "103 092 501"

AsChunks(): https://stackoverflow.com/a/22452051/538763

ToCsv(): https://stackoverflow.com/a/45891332/538763

For a dividing a string and returning a list of strings with a certain char number per place, here is my function:

public List<string> SplitStringEveryNth(string input, int chunkSize)
{
var output = new List<string>();
var flag = chunkSize;
var tempString = string.Empty;
var lenght = input.Length;
for (var i = 0; i < lenght; i++)
{
if (Int32.Equals(flag, 0))
{
output.Add(tempString);
tempString = string.Empty;
flag = chunkSize;
}
else
{
tempString += input[i];
flag--;
}


if ((input.Length - 1) == i && flag != 0)
{
tempString += input[i];
output.Add(tempString);
}
}
return output;
}

You can try something like this using Linq.

var str = "11223344";
var bucket = 2;
var count = (int)Math.Ceiling((double)str.Length / bucket);
        

Enumerable.Range(0, count)
.Select(_ => (_ * bucket))
.Select(_ => str.Substring(_,  Math.Min(bucket, str.Length - _)))
.ToList()

You can also use the StringReader class to reads a block of characters from the input string and advances the character position by count.

StringReader Class Read(Char[], Int32, Int32)

The simplest way to separate thousands with a space, which actually looks bad, but works perfect, would be:

yourString.ToString("#,#").Replace(',', ' ');

I went through all the comments and decided to build this extension method:

public static string FormatStringToSplitSequence(this string input, int splitIndex, string splitCharacter)
{
if (input == null)
return string.Empty;


if (splitIndex <= 0)
return string.Empty;


return string.Join(string.Empty, input.Select((x, i) => i > 0 && i % splitIndex == 0 ? string.Format(splitCharacter + "{0}", x) : x.ToString()));
}

Example:

var text = "24455";
var result = text.FormatStringToSplitSequence(2, ".");

Output: 24.45.5