When working in C#, most of the times you need to manipulate strings. Manipulating strings or editing strings either by replacing some text of string with some other text or just by removing some text from it. So, in next two articles, I will be talking about different methods which you can use to manipulate things. In this article, I will focus on How can we
- Replace Some Part Of String With Another String
- Replace All The Occurrences Of A Substring With Another String
- Replace All The Characters With Another Character Or String
For example purpose, I will be using a string variable which is declared and defined as follows
string myString = "How To Ideas";
- If you want to replace some part of string with another string, then you can try the following code, in which I have replaced ‘To’ from the sample string with ’Many’ and result is stored in another string str1.
string str1 = myString.Replace("To", "Many");
string str2 = Regex.Replace(myString, "To", "Many");
- If you just want to insert some text in your source string at a specified position (say before ‘To’ in my string), then you can try the following code
string str3 = myString.Insert(myString.IndexOf("To"), "Many ");
- Now 1st method will replace all the occurrences of ‘To’ keyword in the sample string with ‘many’. But in some case you just want to replace single occurrence of your substring or character to replace with another string. In that case you need to know the index of starting character of the substring which you want to remove in your source string.
- Say if I want to remove ‘o’ character from my sample string, then there are two occurrences of ‘o’ in my sample string, but I just want to remove the first instance of ‘o’, So you can try the following code
string str5 = myString.Remove(myString.IndexOf("o"), 1).Insert(myString.IndexOf("o"), "p");
string str6 = myString.Remove(1, 1).Insert(1, "p");
- If you want to remove the last occurrence of some string from source string, then you can try the following code
string str7 = myString.Remove(myString.LastIndexOf("o"), 1).Insert(myString.LastIndexOf("o"), "p");
string str7 = myString.Remove(5,1).Insert(5,"p");
- But the substring you want to remove is neither present at first occurrence nor at last occurrence, then you need to have the index of that occurrence in the source string, only then you can replace that string with other string.