Home > Software design >  c# add comma before every numbers in my string except first number
c# add comma before every numbers in my string except first number

Time:02-03

I am developing as application in asp.net mvc.

I have a string like below

string myString = "1A5#3a2@"

now I want to add a comma after every occurrence of number in my string except the first occurrence.

like

string myNewString "1A,5#,3a,2@";

I know I can use loop for this like below myNewString

foreach(var ch in myString) 
{
    if (ch >= '0' && ch <= '9')     
    {                  
        myNewString = myNewString ==""?"":myNewString   ","   Convert.ToString(ch);
    }     
    else     
    {         
        myNewString = myNewString ==""? Convert.ToString(ch): myNewString   Convert.ToString(ch);     
    }
}

CodePudding user response:

so, as I understood the below code will work for you

StringBuilder myNewStringBuilder = new StringBuilder();
foreach(var ch in myString) 
{
    if (ch >= '0' && ch <= '9')     
    {                  
        if (myNewStringBuilder.Length > 0)
        {
            myNewStringBuilder.Append(",");
        }
        myNewStringBuilder.Append(ch);
    }     
    else     
    {         
        myNewStringBuilder.Append(ch);    
    }
}
myString = myNewStringBuilder.ToString();

NOTE

Instead of using myNewString variable, I've used StringBuilder object to build up the new string. This is more efficient than concatenating strings, as concatenating strings creates new strings and discards the old ones. The StringBuilder object avoids this by efficiently storing the string in a mutable buffer, reducing the number of object allocations and garbage collections.

CodePudding user response:

You could use this StringBuilder approach:

public static string InsertBeforeEveryDigit(string input, char insert)
{
    StringBuilder sb = new(input);
    for (int i = sb.Length - 2; i >= 0; i--)
    {
        if (!char.IsDigit(sb[i]) && char.IsDigit(sb[i 1]))
        {
            sb.Insert(i 1, insert);
        }
    }

    return sb.ToString();
}

 Console.Write(InsertBeforeEveryDigit("1A5#3a2@", ',')); // 1A,5#,3a,2@

Update: This answer gives a different result than the one from TWM if the string contains consecutive digits like here: "12A5#3a2@". My answer gives: 12A,5#,3a,2@, TWM's gives: 1,2A,5#,3a,2@. Not sure what is desired.

CodePudding user response:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

  • Related