c#

C# String.IndexOf()方法怎么使用

小亿
116
2023-10-18 14:52:16
栏目: 编程语言

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); // 输出:-1,未找到匹配项

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

0
看了该问题的人还看了