是否有 IndexOf(任何白色字符,startIndex)之类的东西?

is there such a thing as IndexOf(any white character, startIndex)?

白色 space 字符是单个 space、制表符、return 和换行符。要检测这些,请使用此正则表达式:\s

我的问题是:有没有办法让我使用单个 IndexOf 语句 return 任何白色 space 字符的索引?

//works
int index = richTextBox1.Text.IndexOf(' ', 0);
int index = richTextBox1.Text.IndexOf('\n', 0);

//doesn't work
int index = richTextBox1.Text.IndexOf('\s', 0);
int index = richTextBox1.Text.IndexOf("\s", 0);

'\S' 会导致出现字符过多的错误,而“\s”最终会在字符串中查找 \s,而只是在 "heaven" 中查找 a。我不介意检查每种类型,但如果有更好的方法,请告诉我。 谢谢。

string.IndexOfAny(char[]) 将为您提供数组中任何字符的第一个字符出现的字符串的索引。

诀窍在于定义 "whitespace" 是什么。下面的示例将 25 个字符定义为空格,更常见的是 ' ', '\n', '\t', '\v', '\r'。下面将使用 unicode 定义和 char.IsWhitespace 来确定有哪些空白字符。

public static void Main()
{
    var wsChars = Enumerable.Range(0, ushort.MaxValue)
                            .Where(c => char.IsWhiteSpace(Convert.ToChar(c)))
                            .Select(c => Convert.ToChar(c)).ToArray();

    Console.WriteLine(wsChars.Length);

    var someText = "This_is_a\tstring with \nsome whitespace characters.";

    Console.WriteLine(someText.IndexOfAny(wsChars));
}

Try it out on .NET Fiddle

如果您想从特定索引开始,只需使用 string.IndexOfAny(char[], int) 提供起始索引。