Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# add comma before every numbers in my string except first number

I am developing as application in asp.net mvc.

I have a string like below

string myString = "1A5#3a2@"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading