新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C# String.IndexOf()方法如何使用

发布时间:2023-10-18 14:52:16

C# String.IndexOf()方法如何使用

C#中的String.IndexOf()方法用于在字符串中查找指定字符或子字符串的第一个匹配项,并返回其索引位置。该方法有多种重载情势,可以根据区分的需求使用。
以下是常见的使用方式:

  1. 查找单个字符的索引位置:
string str = "Hello World";
int index = str.IndexOf('o');
Console.WriteLine(index); // 输出:4
  1. 查找子字符串的索引位置:
string str = "Hello World";
int index = str.IndexOf("World");
Console.WriteLine(index); // 输出:6
  1. 指定开始搜索的索引位置:
string str = "Hello World";
int index = str.IndexOf('o', 5); // 从索引位置为5的字符开始搜索
Console.WriteLine(index); // 输出:7
  1. 指定搜索的范围:
string str = "Hello World";
int index = str.IndexOf("World", 0, 6); // 从索引位置为0到5的子字符串范围内搜索
Console.WriteLine(index); // 输出:⑴,未找到匹配项

需要注意的是,如果未找到匹配项,则IndexOf()方法会返回⑴。如果要查找多个匹配项的索引位置,可使用循环结合IndexOf()方法进行迭代搜索。