C# 检查字符串之间(或任何地方)是否有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8887794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:58:16  来源:igfitidea点击:

Check if string has space in between (or anywhere)

c#

提问by GurdeepS

Is there a way to determine if a string has a space(s) in it?

有没有办法确定字符串中是否有空格?

sossjjs sskkkshould return true, and sskskjskshould return false.

sossjjs sskkk应该返回true,并且sskskjsk应该返回false。

"sssss".Trim().Lengthdoes not seem to work.

"sssss".Trim().Length似乎不起作用。

采纳答案by Mike Christensen

How about..

怎么样..

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

回答by Russ Cam

Trim()will only remove leading or trailing spaces.

Trim()只会删除前导或尾随空格。

Try .Contains()to check if a string contains white space

尝试.Contains()检查字符串是否包含空格

"sossjjs sskkk".Contains(" ") // returns true

回答by David Clarke

It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.

当您想要测试任何空白字符而不仅仅是空格时,也可以使用正则表达式来实现这一点。

var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true

回答by Farid Movsumov

This functions should help you...

此功能应该可以帮助您...

bool isThereSpace(String s){
    return s.Contains(" ");
}

回答by Dave

How about:

怎么样:

myString.Any(x => Char.IsWhiteSpace(x))

Or if you like using the "method group" syntax:

或者,如果您喜欢使用“方法组”语法:

myString.Any(Char.IsWhiteSpace)