简体   繁体   English

使用String.Concat时如何保留空格

[英]How to keep white spaces when using String.Concat

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. 但是,我想阻止Concat方法删除空格,并且Concat方法不会采用多个参数。 Suggestions? 建议? Perhaps Regex would be smarter? 也许正则表达会更聪明?

空格字符不是字母或数字,因此您需要更改Where子句,例如:

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

It's not the Concat that is removing whitespaces. 这不是Concat正在删除空格。 Where is removing whitespaces, because whitespaces are neither letters not digits. Where被删除空格,空格,因为既不是字母数字没有。

You just need to modify the Where : 你只需要修改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用空字符串替换上面的内容,你会得到结果:

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

你是对的,你可以使用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. 从用户的角度来看,这非常令人困惑并且可能导致不必要的行为,最好是验证输入并向用户显示他输入的内容无效的通知/信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM