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

后端 未结 11 1876
执念已碎
执念已碎 2020-12-17 09:27

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

11条回答
  •  抹茶落季
    2020-12-17 10:22

    There is a very simple solution

    string test = "    hello world";
    int pos = test.ToList().FindIndex(x => char.IsWhiteSpace(x) == false);
    

    pos will be 4

    you can have more complex conditions like:

    pos = test.ToList().FindIndex((x) =>
                    {
                        if (x == 's') //Your complex conditions go here
                            return true;
                        else 
                            return false;
                    }
                );
    

提交回复
热议问题