【问题标题】:is there such a thing as IndexOf(any white character, startIndex)?是否有 IndexOf(任何白色字符,startIndex)之类的东西?
【发布时间】:2019-05-29 15:24:43
【问题描述】:

空白字符是单个空格、制表符、回车和换行符。要检测这些,请使用以下正则表达式:\s

我的问题是:有没有办法让我使用单个 IndexOf 语句来返回任何空白字符的索引?

//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。我不介意检查每种类型,但如果有更好的方法,请告诉我。 谢谢。

【问题讨论】:

  • 正则表达式:\s 如果你知道,为什么不使用正则表达式???
  • 您可以将string.IndexOfAny(char[]) 与可能的空白字符组成的char 数组一起使用。
  • 关闭时我正在发布答案,但在 DotNetFiddle 上here, you can try it out。
  • 对不起 TaW 和 Camilo,但我对 IndexOf 特别感兴趣,所以我不知道为什么我丢了分。我正在寻找 IndexOf 答案/主题。所以感谢@RonBeyer 的回答。我会马上检查的

标签: c# regex indexof


【解决方案1】:

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

诀窍在于定义什么是“空白”。下面的示例将 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) 提供起始索引即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多