How To Ideas | How To Articles | How To Tutorials


0

How To Remove A Substring From A String In C#


Continuing my discussion on manipulating strings in C#, In this article I will talk about different ways which we can use to remove substring from a string in C#.

I will be using the following string as source string for example purpose.

string myString = "How To Ideas";

Instructions:

  1. If you want to remove all the occurrences of a substring from your source string, then you can try the following code which will replace all the occurrences of “o” from my source string.

    string str1 = myString.Replace("o", "");

  2. If you want to remove the whole text present after specified substring from your string, then you can try the following code, which will replace all the text after “To” substring from my source string

    string str2 = myString.Remove(myString.IndexOf("To") + "To".Length);

    or just

    string str2 = myString.Remove(myString.IndexOf("To") + 2);

  3. If you want to remove “To” as well in upper example, then try following code

    string str3 = myString.Remove(myString.IndexOf("To") );

  4. If you just want to remove some part of text, then you need to know the index of starting character of that substring in your source string. Following code will remove “To” substring from my source string

    string str4 = myString.Remove(myString.IndexOf("To"), 2);

Here is the output in Console window of all the strings after running all the code lines discussed above
Remove Substring From A String

Incoming search terms:

  • C program to delete a substring from a text (2)
  • how to remove substring from string in c# (1)
Filed in: C# Tags: , , , , , , , ,

Leave a Reply

Submit Comment



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