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

后端 未结 11 1892
执念已碎
执念已碎 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:17

    var match = Regex.Match(" \t test  ", @"\S"); // \S means all characters that are not whitespace
    if (match.Success)
    {
        int index = match.Index;
        //do something with index
    }
    else
    {
        //there were no non-whitespace characters, handle appropriately
    }
    

    If you'll be doing this often, for performance reasons you should cache the compiled Regex for this pattern, e.g.:

    static readonly Regex nonWhitespace = new Regex(@"\S");
    

    Then use it like:

    nonWhitespace.Match(" \t test  ");
    

提交回复
热议问题