获得第一个非空格字符指数在C#中的字符串

问题描述:

有没有拿到的第一个非空格字符的字符串中的索引(或更一般,第一个字符匹配条件的指数)在C#中没有写我自己的循环代码的方法?

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;

        i++;
    }

    return -1;
}

您可以再使用LINQ来解决原来的问题:

You could then use LINQ to address your original problem:

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