C# Remove a Character from String

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#:

  1. using System;
  2. namespace CSharp_Remove_Character_From_String
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string str1 = "Learn C# programming language!";
  9. str1 = str1.Replace("#", "");
  10. Console.WriteLine("str1:{0}", str1);
  11. //
  12. string str2 = "*#@ Online C programming tutorials !@.$";
  13. string[] charactersToRemove = { ".", "@", "!", "#", "$", "*" };
  14. foreach (string character in charactersToRemove)
  15. {
  16. str2 = str2.Replace(character, "");
  17. }
  18. //
  19. Console.WriteLine("str2:{0}", str2);
  20. }
  21. }
  22. }

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:

  1. using System;
  2. namespace CSharp_Remove_Character_From_String
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string str1 = "Learn C# programming language!";
  9. str1 = string.Join("", str1.Split('#'));
  10. Console.WriteLine("str1:{0}", str1);
  11. //
  12. string str2 = "*#@ Online C programming tutorials !@.$";
  13. str2 = string.Join("", str2.Split('.', '@', '!', '#', '$', '*'));
  14. //
  15. Console.WriteLine("str2:{0}", str2);
  16. }
  17. }
  18. }
  19.  

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.


See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# Variables