Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep white spaces when using String.Concat

Tags:

string

c#

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?

like image 988
miniHessel Avatar asked Jun 21 '26 07:06

miniHessel


2 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 == ' '));
like image 67
DavidG Avatar answered Jun 23 '26 20:06

DavidG


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]", "")
like image 23
Sweeper Avatar answered Jun 23 '26 21:06

Sweeper