OneBite.Dev - Coding blog in a bite size

Remove A Character From A String In C#

Code snippet for how to Remove A Character From A String In C# with sample and detail explanation

Working on string manipulation is one of the basic functionalities in every programming language. In this article, we’ll cover how to remove a specific character from a string in C#.

Code snippet for removing a character from a string

Let’s consider the following code that removes a character from a string:

string originalString = "Hello, World!";
char charToRemove = 'o';
string modifiedString = new string(originalString.ToCharArray().Where(c => c != charToRemove).ToArray());
Console.WriteLine(modifiedString);

This code will output: “Hell, Wrld!”

Code Explanation for removing a character from a string

Let’s go through the code step by step to fully understand its mechanism.

  1. We first declare originalString, which represents the initial string from which we will remove a character.
string originalString = "Hello, World!";
  1. Next, we declare charToRemove that specifies the character we want to remove from the string:
char charToRemove = 'o';
  1. The most important step is the creation of modifiedString. In this line, we are converting the original string to a character array, filtering out the character we want to remove and then converting this array back to a string:
string modifiedString = new string(originalString.ToCharArray().Where(c => c != charToRemove).ToArray());

We use the LINQ Where method to filter out the required character. The lambda expression c => c != charToRemove is used as a predicate to select all the characters which are not equal to charToRemove. This construct effectively removes the specified character.

  1. Finally, we output the modifiedString to the console to see the result:
Console.WriteLine(modifiedString);

This will produce: “Hell, Wrld!”, which is the original string without ‘o’ characters.

This simple C# code snippet exhibits how to remove a certain character from a string. This basic task allows you to understand string manipulation in C# at a deeper level.

c-sharp