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

I asked a question about removing spaces and tabs. Now I have something else. I need to check if the first character of the string is a space or tab. Can anyone think of a good way to do this.

Thanks,

+6
source share
8 answers

The best way is to use the Char.IsWhiteSpace method:

 // Normally, you would also want to check that the input is valid (eg not null) var input = "blah"; var startsWithWhiteSpace = char.IsWhiteSpace(input, 0); // 0 = first character if (startsWithWhiteSpace) { // your code here } 

The method documentation explicitly states what exactly is considered a space; if for any reason this list of characters does not meet your needs, you will have to do a more rigorous manual check.

+12
source

You can check it as follows:

 if( myString[0] == ' ' || myString[0] == '\t' ){ //do your thing here } 

This will crash for emtpy and null strings, so you should probably make it more secure, for example:

 if( !string.IsNullOrEmpty(myString) && (myString[0] == ' ' || myString[0] == '\t') ){ //do your thing here } 
+6
source

I would just go with something like:

 if (str.StartsWith(" ") || str.StartsWith("\t")) { ... } 

or

 if ((str[0] == ' ') || (str[0] == "\t")) { ... } 

I really prefer the former, since you don't have to worry about issues with empty strings.

If you want to handle a more complicated case in the future, you can use regular expressions, for example:

 if (Regex.IsMatch (str, @"^\s")) ... 

This can be changed to handle arbitrarily complex cases, although it is a bit like killing flies with a thermonuclear warhead for your specific case.

+4
source

If you are interested in not only the space and the tab, but also the spaces in general, use this:

 if(!string.IsNullOrEmpty(myString) && char.IsWhiteSpace(myString[0])) // It a whitespace 
+3
source
 if (text[0] == ' ' || text[0] == '\t') 
+1
source

And just for fun:

 if (Regex.IsMatch(input, @"^\s")) { // yep, starts with whitespace } 

Please note that while many other answers will fail when setting an empty line, this one will work and it will be easily extensible to fit more complex things than just spaces at the beginning of the line. Some people find that regular expressions are overflowing for simple checks, but others suggest that if you want to match patterns one by one, you should use regular expressions.

+1
source
 if(myString[0]==' ' || myString[0]=='\t') { //do something } 
+1
source

You need to import the System.Linq namespace.

 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. } 
0
source

Source: https://habr.com/ru/post/895840/


All Articles