Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if the first character of my string is a space or tab character?

Tags:

c#

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,

like image 995
Jason Avatar asked Aug 25 '11 08:08

Jason


2 Answers

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.

like image 173
Jon Avatar answered Sep 21 '22 08:09

Jon


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
}
like image 40
Øyvind Bråthen Avatar answered Sep 20 '22 08:09

Øyvind Bråthen