C# Tutorial - String Replace





Part 39 C# String Replace






String.Replace method which is used to replace with the specific unicode character. 






  • string Replace is immutable i.e the string you can change into another object of string.

       public String Replace(char oldChar, char newChar);

        public String Replace(String oldValue, String newValue);
     

  When occur Exceptions:.

System.ArgumentNullException:
        //     oldValue is null.
       
System.ArgumentException:
        //     oldValue is the empty string ("").

  1. public String Replace(char oldChar, char newChar);

 public class Program

    {


        {
            String data = "Csharp-tutorial-point.blogspot.com";
            Console.WriteLine("The initial string: '{0}'", data);

           //Here we replace '-' from space.
            data = data.Replace("-", " ");

           //here this multiple replacement 
            data = data.Replace("t", "T").Replace("p", "P").Replace("b", "B");

            Console.WriteLine("The final string: '{0}'", data);
            Console.ReadLine();
        }
    }



Output :

The initial string  : 'Csharp-tutorial-point.blogspot'
The final string  : 'Csharp tutorial point.blogspot'
The final string  : 'CsharP TuTorial PoinT.BlogsPoT'

2. public String Replace(String oldValue, String newValue);

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.


 public class Program

    {


        {
            String data = "Csharp-tutorial-point.blogspot";
            Console.WriteLine("The initial string  : '{0}'", data);

//here we replaced  '.blogspot' with empty
            data = data.Replace(".blogspot", " ");

            Console.WriteLine("The final string  : '{0}'", data);
            Console.ReadLine();
        }
    }