How to keep white spaces when using String.Concat

Viewed 1199

To prevent the user from inputting anything besides letter or numbers, I am using

string.Concat(textbox.Text.Where(char.IsLetterOrDigit ));

However, I would like to prevent the Concat method from removing white spaces, and the Concat method does not take multiple arguments. Suggestions? Perhaps Regex would be smarter?

4 Answers

The space character isn't a letter or a digit so you need to change your Where clause, for examples:

string.Concat(textbox.Text.Where(c => char.IsLetterOrDigit(c) || c == ' '));

It's not the Concat that is removing whitespaces. Where is removing whitespaces, because whitespaces are neither letters not digits.

You just need to modify the Where:

string.Concat(textbox.Text.Where(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x) ));

Since you mentioned regex, here is a regex to do it:

[^\p{L}\p{Nd}\s]

Regex.Replace the above with an empty string and you will get the result:

Regex.Replace(input, "[^\\p{L}\\p{Nd}\\s]", "")

You're right, you can use regex

Regex.Replace(textbox.Text, @"[^a-zA-Z0-9]", "");

To prevent the user from inputting anything besides letter or numbers, I am using...

Actually you do not prevent the user from entering anything, instead you transform/filter the input the user made (and remove unwanted characters there). From a user's perspective, this is quite confusing and might lead to unwanted behavior, would be better to validate the input and show the user some notification/info that what he has entered was not valid.

Related