How to replace a char in string without using string replace method in c#

Q:Lets take a example like, given string is "a,b,c,d". Please Replace comma(',') with semicolon (';') without using string replace method of c#.

A: Keep in mind always, String are immutable so you cannot change easily like just find the ',' in string and replace it with ';'. 

If you will try to do in this way, you will get the below error


CS0200: Property or indexer 'string.this[int]' cannot be assigned to -- it is read only

Correct way to replace specific char in the string is given below.

class Program

    {

        static void Main()

        {

            //Replace , with ; 

            string str = "a,b,c,d";

            string newstr = string.Empty;

            foreach (char item in str)

            {

                if (item == ',')

                {

                    newstr = newstr+';';

                }

                else

                {

                    newstr = newstr + item;

                }

            }            

            Console.WriteLine(newstr);

        }

    }


If you have any better solution then please share.✋

Hope, It is helpful.

No comments:

Post a Comment

Your feedback is important.
Visit www.techwebdots.in