How to remove unnecessary characters from C# strings
In various programming scenarios, you may need to remove specific characters from a string. Consider the following example:
Suppose you have a string: "My name @is ,Wan.;';Wan". You want to remove the characters "@", ",", ".", ";" and "'" from the string to get "My name is Wan Wan".
Method 1: Iterative deletion
One way is to iterate through each character in the string and use the Replace method to remove the specified character. Here's how you can do it:
<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>
Method 2: Deletion based on regular expressions
Alternatively, you can use regular expressions to remove all non-alphabetic characters. Here's a more comprehensive method that will remove any characters that are not spaces, letters, or numbers:
<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>
This will get the result "My name is Wan Wan".
The above is the detailed content of How Can I Efficiently Remove Specific or Non-Alphanumeric Characters from a C# String?. For more information, please follow other related articles on the PHP Chinese website!