How to remove a character from a string in C#
In this tutorial, you will learn how to remove a character from a string in C#.
More tutorials:
Removing a character from a string with the string Replace() method
To replace each character in a string, use the Replace() method; C# allows you to remove characters in a string by replacing them with an empty string.
The following code example demonstrates the use of the string Replace() method to remove characters in C#:
using System; namespace CSharp_Remove_Character_From_String { class Program { static void Main(string[] args) { string str1 = "Learn C# programming language!"; str1 = str1.Replace("#", ""); Console.WriteLine("str1:{0}", str1); // string str2 = "*#@ Online C programming tutorials !@.$"; string[] charactersToRemove = { ".", "@", "!", "#", "$", "*" }; foreach (string character in charactersToRemove) { str2 = str2.Replace(character, ""); } // Console.WriteLine("str2:{0}", str2); } } }
Output:
str1:Learn C programming language!
str2: Online C programming tutorials
Removing characters from a string with the string Join() and Split()
A combination of string Join() and Split() can be used to remove characters from a string.
The following code example shows how to use the C# string Join() and Split() functions to remove multiple characters from a string:
using System; namespace CSharp_Remove_Character_From_String { class Program { static void Main(string[] args) { string str1 = "Learn C# programming language!"; str1 = string.Join("", str1.Split('#')); Console.WriteLine("str1:{0}", str1); // string str2 = "*#@ Online C programming tutorials !@.$"; str2 = string.Join("", str2.Split('.', '@', '!', '#', '$', '*')); // Console.WriteLine("str2:{0}", str2); } } }
Output:
str1:Learn C programming language!
str2: Online C programming tutorials
Summary
This tutorial explained how to remove a character from a string by using the string Replace() method and the combination of the string Join() and Split() methods.