Reputation: 227
I asked a question about removing spaces and tabs. Now I have something else needed. I need to be able to check if the first character of a string is a space or tab. Can anyone think of a good way to do this.
Thanks,
Upvotes: 9
Views: 24177
Reputation: 882616
I would just go with something like:
if (str.StartsWith(" ") || str.StartsWith("\t")) {
...
}
or:
if ((str[0] == ' ') || (str[0] == "\t")) {
...
}
I actually prefer the former since you don't have to worry about problems with empty strings.
If you want to handle more complex case in future, you could use regular expressions, something like:
if (Regex.IsMatch (str, @"^\s")) ...
This can be modified to handle arbitrarily complex cases, though it's a bit like killing flies with a thermo-nuclear warhead for your particular case.
Upvotes: 6
Reputation: 1535
You'll need to have the System.Linq
namespace imported.
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.
}
Upvotes: 0
Reputation: 174457
If you are not only interested in space and tab but in whitespace in general, use this:
if(!string.IsNullOrEmpty(myString) && char.IsWhiteSpace(myString[0]))
// It's a whitespace
Upvotes: 6
Reputation: 437804
The best way is to use the Char.IsWhiteSpace
method:
// 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
}
The method's documentation explicitly mentions what exactly is considered white space; if for some reason that list of characters does not suit your needs, you will have to do a more restrictive check manually.
Upvotes: 16
Reputation: 60276
And just for fun:
if (Regex.IsMatch(input, @"^\s")) {
// yep, starts with whitespace
}
Note that while many of the other answers will fail when given an empty string, this one will work, and it would be easily extensible to match more complex things than just whitespace at the beginning of the string. Some people find regexes to be overkill for simple checks, but others believe that if you want to do pattern matching on strings, you should use regexes.
Upvotes: 2
Reputation: 60744
You can check it like this:
if( myString[0] == ' ' || myString[0] == '\t' ){
//do your thing here
}
This will fail for emtpy and null strings, so you should probably make it a bit more secure like this:
if( !string.IsNullOrEmpty(myString) && (myString[0] == ' ' || myString[0] == '\t') ){
//do your thing here
}
Upvotes: 6