Inserting, Replacing and Removing in string using C#

This article show that how to use Insert(), Replace() and Remove() method in C#.


We can insert a string into another string using the Insert() method , shown here:
Public string Insert(int start, string str)
In above expression str is inserted into invoking string at the index specified by start.


We can remove some portion of a string using Remove() method, shown here:
Public string Remove(int start)
Public string Remove(int start, int count)
Begins at the index specified by start and removes all remaining characters in the string.
The second form begins at start and removes count number of characters.


We can replace a portion of a string by using Replace() method, shown here it has these forms:
Public string Replace(char ch1, char ch2)
Public string Replace(string str1, string str2)
The first form replaces all occurrences of ch1 in the invoking string with ch2. Secod form replace all occurrences of str1 in the invoking string with str2.



string mainString = “Welcome Authorcode”;

//——Inserting String –Add ‘TO’ after ‘Welcome’————-
mainString = mainString.Insert(9, “To”);
// value of mainstring= “Welcome To Authorcode”

//—–Replacing string–replace ‘Authorceode’ to ‘My Home’———-
mainString = mainString.Replace(“Authorcode”, “My Home”);
// value of mainstring= “Welcome To My Home”

//—–Replacing character–replace ‘O’ to ‘Y’
mainString = mainString.Replace(“O”, “Y”);
// value of mainstring= “WelcYme TY My HYme”

//—–Remove character–replace ‘Y’
mainString = mainString.Remove(4, 6);
// value of mainstring= “Welc My HYme”