Splitting a string / number every Nth Character /

2019-01-03 16:42发布

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.

13条回答
ゆ 、 Hurt°
2楼-- · 2019-01-03 17:24

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;
    }
查看更多
登录 后发表回答