[英]How can I check if the first character of my string is a space or tab character?
我问了一个关于删除空格和制表符的问题。 现在我还需要其他东西。 我需要能够检查字符串的第一个字符是空格还是制表符。 任何人都可以想到一个很好的方法来做到这一点。
谢谢,
最好的方法是使用Char.IsWhiteSpace
方法:
// Normally, you would also want to check that the input is valid (e.g. not null)
var input = "blah";
var startsWithWhiteSpace = char.IsWhiteSpace(input, 0); // 0 = first character
if (startsWithWhiteSpace)
{
// your code here
}
该方法的文档明确提到了什么是白色空间; 如果由于某种原因,字符列表不符合您的需要,您将不得不手动进行更严格的检查。
你可以这样检查:
if( myString[0] == ' ' || myString[0] == '\t' ){
//do your thing here
}
对于emtpy和null字符串,这将失败,所以你应该让它更安全,如下所示:
if( !string.IsNullOrEmpty(myString) && (myString[0] == ' ' || myString[0] == '\t') ){
//do your thing here
}
我会选择以下内容:
if (str.StartsWith(" ") || str.StartsWith("\t")) {
...
}
要么:
if ((str[0] == ' ') || (str[0] == "\t")) {
...
}
我实际上更喜欢前者,因为你不必担心空字符串的问题。
如果您希望将来处理更复杂的案例,可以使用正则表达式,例如:
if (Regex.IsMatch (str, @"^\s")) ...
这可以修改为处理任意复杂的情况,虽然这有点像为你的特定情况杀死带有热核弹头的苍蝇。
如果您不仅对空间和制表符感兴趣,而且通常在空白中,请使用:
if(!string.IsNullOrEmpty(myString) && char.IsWhiteSpace(myString[0]))
// It's a whitespace
if (text[0] == ' ' || text[0] == '\t')
而且只是为了好玩:
if (Regex.IsMatch(input, @"^\s")) {
// yep, starts with whitespace
}
请注意,虽然许多其他答案在给定空字符串时会失败,但是这个答案会起作用,并且它很容易扩展以匹配比字符串开头的空格更复杂的东西。 有些人发现正则表达式对于简单检查来说是过度杀伤,但是其他人认为如果你想对字符串进行模式匹配,你应该使用正则表达式。
if(myString[0]==' ' || myString[0]=='\t')
{
//do something
}
您需要导入System.Linq
命名空间。
var firstToken = yourString.FirstOrDefault();
if (firstToken == ' ' || firstToken == '\t')
{
// First character is a space or tab
}
else
{
// First character is not a space or tab, or string is empty.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.