Eric J. Eric J. - 4 months ago 39
C# Question

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

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?


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.


I like to define my own extension method for returning the index of the first element that satisfies a custom predicate in a sequence.

/// <summary>
/// Returns the index of the first element in the sequence 
/// that satisfies a condition.
/// </summary>
/// <typeparam name="TSource">
/// The type of the elements of <paramref name="source"/>.
/// </typeparam>
/// <param name="source">
/// An <see cref="IEnumerable{T}"/> that contains
/// the elements to apply the predicate to.
/// </param>
/// <param name="predicate">
/// A function to test each element for a condition.
/// </param>
/// <returns>
/// The zero-based index position of the first element of <paramref name="source"/>
/// for which <paramref name="predicate"/> returns <see langword="true"/>;
/// or -1 if <paramref name="source"/> is empty
/// or no element satisfies the condition.
/// </returns>
public static int IndexOf<TSource>(this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate)
    int i = 0;

    foreach (TSource element in source)
        if (predicate(element))
            return i;


    return -1;

You could then use LINQ to address your original problem:

string str = "   Hello World";
int i = str.IndexOf<char>(c => !char.IsWhiteSpace(c));