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:
- 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", ""); - 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); - If you want to remove “To” as well in upper example, then try following code
string str3 = myString.Remove(myString.IndexOf("To") ); - 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 ![]()
Incoming search terms:
- C program to delete a substring from a text (2)
- how to remove substring from string in c# (1)
Related posts:
How To Replace A Substring With Some Text In A String In C# How To Find All The Occurrences Of A String Within Another String In C# How To Search A String Within Another String In C# How To Check Whether A String Starts Or Ends With A Specified String In C# How To Perform Searching In String In C#