空白字符是单个空格、制表符、回车和换行符。要检测这些,请使用以下正则表达式:\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。我不介意检查每种类型,但如果有更好的方法,请告诉我。谢谢你。
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));
}
如果要从特定索引开始,只需使用string.IndexOfAny(char[], int)
提供起始索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句