Search code examples
c#stringinsertlinefeed

How to add a line feed after each digit that came before a letter


i have a string like that:

String s ="6,44 6,35    +0,63asd    4,27fgh 4,14  45,6 +777,4cvbvc";

I want to insert a line feed into those points between every digit and letter like: +0,63(here must be a line break)asd. I wrote the code below but it gave length changed error. Maybe it may occur either because of my program's features or c#'s feature. But i need to stay stick to the features. So can you recommend me a solution in those limits? The code below could not solve it and i could not find any other way.

int k = s.Length;
for (int i = 0; i < k; i++)
            if (char.IsDigit(s[i - 1]) && char.IsLetter(s[i]))
                s = s.Insert(i, Strings.Chr(10).ToString());

Thank you for your help. Cheers.


Solution

  • You need to start the cycle from 1 or you will get an exception because when i=0 s[i-1] becomes s[-1]. Now your program should work but i would suggest you to use a stringbuilder because string.Insert creates a new string instance everytime you call it making your program very slow if the input string is long. Also if you are in a Windows environment a line break is represented by "\r\n" wich is Environment.NewLine in c#. So your code should be something like this:

    StringBuilder builder=new StringBuilder(s);
    int offset=0;
    for (int i = 1; i < s.Length; i++)
    {
        if (char.IsDigit(s[i - 1]) && char.IsLetter(s[i]))
        {
            builder.Insert(i+offset, Environment.NewLine);
            //every time you add a line break you need to increment the offset
            offset+=Environment.NewLine.Length;
        }
    }
    s=builder.ToString();