Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Index of First non-Whitespace Character in C# String

Tags:

Is there a means to get the index of the first non-whitespace character in a string (or more generally, the index of the first character matching a condition) in C# without writing my own looping code?

EDIT

By "writing my own looping code", I really meant that I'm looking for a compact expression that solves the problem without cluttering the logic I'm working on.

I apologize for any confusion on that point.

like image 691
Eric J. Avatar asked Oct 02 '12 17:10

Eric J.


People also ask

What is the index of the first non-white space character?

The index of the first non-white space character is the difference between the length of the original string and the trimmed one. Basically, if you are looking for a limited set of chars (let's say digits) you should go with the first method.

How to check if a character is white space in C++?

A white-space character can be a space (’ ’), horizontal tab (‘ ’), newline (‘ ’), vertical tab (‘\v’), feed (‘\f’) or carriage return (‘’). We will use isspace () function to check that. This function is defined is ctype header file.

How to count the number of whitespace characters in a string?

This function is used to check if the argument contains any whitespace characters. Given a string, we need to count the number of whitespace characters in the string using isspace () function. Application: isspace () function is used to find number of spaces in a given sentence.

How to remove all white space characters from the beginning of string?

Alternatively, you can use the String.TrimStart function which remove all white space characters from the beginning of the string. The index of the first non-white space character is the difference between the length of the original string and the trimmed one.


1 Answers

A string is of course an IEnumerable<char> so you can use Linq:

int offset = someString.TakeWhile(c => char.IsWhiteSpace(c)).Count(); 
like image 168
Henk Holterman Avatar answered Oct 26 '22 20:10

Henk Holterman