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

   2025-02-15 9350
核心提示:C#中的String.IndexOf()方法用于在字符串中查找指定字符或子字符串的第一个匹配项,并返回其索引位置。该方法有多种重载形式,可

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

以下是常见的使用方式:

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

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言