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.
Consider the string: "My name @is ,Wan.;'; Wan". We need to remove the characters '@', ',', '.', ';' and ''' to get "My name is Wan Wan."
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>
This method iterates over the characters to be removed and replaces each occurrence with an empty string, effectively removing them from the string.
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>
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!