Remove non alphanumeric | C#

In C#, you can remove all non-alphanumeric characters from a string using different approaches. Non-alphanumeric characters are any characters that are not letters (a-z or A-Z) or digits (0-9). Here are some common methods to achieve this:

Using Regex.Replace()

You can use regular expressions to remove all non-alphanumeric characters from the string:

using System.Text.RegularExpressions; string originalString = "Hello, World! 123"; string pattern = "[^a-zA-Z0-9]"; string stringWithoutNonAlphanumeric = Regex.Replace(originalString, pattern, ""); // Result: "HelloWorld123"

In this example, the regular expression pattern [^a-zA-Z0-9] matches any character that is not a letter or a digit and replaces them with an empty string.

Using LINQ and Char.IsLetterOrDigit()

You can use LINQ with the Char.IsLetterOrDigit() method to filter out non-alphanumeric characters:

using System.Linq; string originalString = "Hello, World! 123"; string stringWithoutNonAlphanumeric = new string(originalString.Where(c => Char.IsLetterOrDigit(c)).ToArray()); // Result: "HelloWorld123"

In this example, the LINQ expression keeps only the characters that are letters or digits, creating a new string from the filtered characters.

Using a loop

You can manually iterate through the characters of the string and build a new string with only alphanumeric characters:

string originalString = "Hello, World! 123"; string stringWithoutNonAlphanumeric = ""; foreach (char c in originalString) { if (Char.IsLetterOrDigit(c)) stringWithoutNonAlphanumeric += c; } // Result: "HelloWorld123"

In this approach, we loop through each character of the original string, and if the character is a letter or a digit, we add it to the new string.

Conclusion

Regardless of the method you choose, keep in mind that strings in C# are immutable, so all these approaches will create a new string without the non-alphanumeric characters rather than modifying the original string. If you need to perform multiple string manipulations, consider using StringBuilder for better performance. Choose the method that best suits your specific requirements and coding style.