How To Ideas | How To Articles | How To Tutorials


0

How To Replace A Substring With Some Text In A String In C#


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

  1. Replace Some Part Of String With Another String
  2. Replace All The Occurrences Of A Substring With Another String
  3. 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";

Instructions:

  1. 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");

    or

    string str2 = Regex.Replace(myString, "To", "Many");

  2. 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 ");

  3. 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.
  4. 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");

    or just

    string str6 = myString.Remove(1, 1).Insert(1, "p");

  5. 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");

    or just

    string str7 = myString.Remove(5,1).Insert(5,"p");

  6. 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.

Here is the snapshot of the output in Console, after running all these commands and just displaying string in Console
Replace Substring With Another String - C#

Filed in: C# Tags: , , , , , , , , ,

Leave a Reply

Submit Comment



© 2013 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.