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,
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With