C# 字符串 - IndexOfAny() 方法
C# 字符串 IndexOfAny() 方法用于检索字符串中指定字符数组中任意字符首次出现的索引。
如果字符串中未找到该字符,则此方法返回 -1。
语法
以下是 C# 字符串 IndexOfAny() 方法的语法 -
public int IndexOfAny(char[] anyOf); public int IndexOfAny(char[] anyOf, int startIndex); public int IndexOfAny(char[] anyOf, int startIndex, int count);
参数
此方法接受以下参数 -
- anyOf:必需参数。表示要在字符串中搜索的字符数组。
- startIndex:可选参数。表示在字符串中开始搜索的起始位置。
- count:可选参数。字符串中要搜索的字符数。
返回值
此方法返回指定数组中任意字符首次出现的索引位置,该索引位置从零开始。
示例 1:默认 IndexOfAny(char[] anyOf) 方法
以下是 IndexOfAny() 方法的基本示例,用于检索字符数组中任意字符首次出现的索引 -
using System; class Program { static void Main() { string str = "Hii, tutorialspoint!"; // 要搜索的字符数组 char[] charsToFind = { 'i', 'o', '!' }; int first_indx = str.IndexOfAny(charsToFind); Console.WriteLine(first_indx); } }
输出
以下是输出 -
1
示例 2:查找字符串中的第一个字符索引
我们来看另一个示例。这里,我们使用 IndexOfAny() 方法在给定字符串的字符数组中查找任意字符首次出现的索引 -
using System; class Program { static void Main() { string str = "Hello, World!"; char[] charsToFind = { 'W', 'o', '!' }; int index = str.IndexOfAny(charsToFind); Console.WriteLine(index); } }
输出
以下是输出 -
4
示例 3:带有 StartIndex 的 IndexOfAny 方法
在此示例中,我们使用 IndexOfAny() 方法从字符串中的字符数组中查找给定起始索引处任意字符的第一个索引 -
using System; class Program { static void Main() { string str = "Hello, tutorialspoint"; char[] charsToFind = { 'W', 'o', 't' }; // 在"Hello, "之后开始搜索 int index = str.IndexOfAny(charsToFind, 7); Console.WriteLine(index); } }
输出
以下是输出 -
7
示例 4:带有 StartIndex 和 Count 的 IndexOfAny() 方法
以下示例使用 IndexOfAny() 方法从给定的 startIndex 开始,仅查找给定计数的字符串中第一次出现的字符的索引 -
using System; class Program { static void Main() { string str = "Hello, tutorialspoint"; char[] charsToFind = { 'W', 'o', 'n' }; // 从索引 7 开始仅搜索 5 个字符 int index = str.IndexOfAny(charsToFind, 7, 5); Console.WriteLine(index); } }
输出
以下是输出 -
10