Home > Backend Development > C++ > How Can I Efficiently Remove Specific Characters from a C# String?

How Can I Efficiently Remove Specific Characters from a C# String?

Mary-Kate Olsen
Release: 2025-01-14 14:32:46
Original
678 people have browsed it

How Can I Efficiently Remove Specific Characters from a C# String?

C# string character removal method

In C#, string manipulation is a common task that usually involves removing specific characters. This may be due to various reasons such as data cleaning or formatting.

Question

Consider the string: "My name @is ,Wan.;'; Wan". We need to remove the characters '@', ',', '.', ';' and ''' to get "My name is Wan Wan."

Solution

In C#, there are several ways to remove characters from a string. One way is to use the Replace method and use an empty string as the replacement:

<code class="language-csharp">var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "@", ",", ".", ";", "'" };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}</code>
Copy after login

This method iterates over the characters to be removed and replaces each occurrence with an empty string, effectively removing them from the string.

Another method

An alternative is to use LINQ to filter out non-letter and space characters:

<code class="language-csharp">var str = "My name @is ,Wan.;'; Wan";
str = new string((from c in str
                  where char.IsWhiteSpace(c) || char.IsLetterOrDigit(c)
                  select c
       ).ToArray());</code>
Copy after login

This method creates a new string containing only space characters or letters and numbers, effectively removing any other characters.

The above is the detailed content of How Can I Efficiently Remove Specific Characters from a C# String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template