I need to split a number into even parts for example:
32427237 needs to become 324 272 37
103092501 needs to become 103 092 501
I'm sure I could just for-next the numbers, but I'm sure there is a more efficient way as I don't want to miss the characters in these numbers - the numbers themselves can be any length so if the number were 1234567890 I'd want it split into these parts 123 456 789 0
I've seen examples in other languages like Python etc but I don't understand them well enough to convert them to C# - looping though the characters and then at the third getting the previous and then that index to get the section of the string may do the job, but I'm open to suggestions on how to accomplish this better.
If you have to do that in many places in your code you can create a fancy extension method:
You can then use it like this:
The output is
324 272 37
as desired.If you know that the whole string's length is exactly divisible by the part size, then use:
But if there's a possibility the whole string may have a fractional chunk at the end, you need to little more sophistication:
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 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:
To join back as a string, delimited by spaces:
Edit: I like Martin Liversage solution better :)
Edit 2: Fixed a bug.
Edit 3: Added code to join the string back.
I like this cause its cool, albeit not super efficient:
You could use a simple for loop to insert blanks at every n-th position: