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.
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.
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.
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.
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.
A string
is of course an IEnumerable<char>
so you can use Linq:
int offset = someString.TakeWhile(c => char.IsWhiteSpace(c)).Count();
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