C# String.IndexOf()方法实例讲解

   2025-02-13 7840
核心提示:IndexOf() 方法是 C# 字符串类的一个方法,用于返回指定字符或字符串在当前字符串中第一次出现的位置。它的语法如下:public int

IndexOf() 方法是 C# 字符串类的一个方法,用于返回指定字符或字符串在当前字符串中第一次出现的位置。它的语法如下:

public int IndexOf(string value)

其中,value 参数是要查找的字符或字符串。该方法返回一个整数值,表示指定字符或字符串第一次出现的索引位置。如果未找到指定字符或字符串,则返回 -1。

下面是一个使用 IndexOf() 方法的示例:

string str = “Hello, World!”;int index = str.IndexOf(“World”);Console.WriteLine(index);

这段代码会在字符串 “Hello, World!” 中查找字符串 “World”,并返回它第一次出现的索引位置。在这个例子中,输出结果为 7,因为 “World” 在字符串中的索引位置是从 7 开始的。

另外,IndexOf() 方法还可以接受一个可选的参数 startIndex,用于指定从哪个索引位置开始查找。例如:

string str = “Hello, World!”;int index = str.IndexOf(“o”, 5);Console.WriteLine(index);

在这个示例中,我们指定从索引位置为 5 的字符开始查找字符 “o”,输出结果为 7,因为第一个 “o” 出现在索引位置 7。

需要注意的是,IndexOf() 方法区分大小写。如果要进行大小写不敏感的查找,可以使用 IndexOf() 方法的重载形式:

public int IndexOf(string value, StringComparison comparisonType)

其中,comparisonType 参数是一个 StringComparison 枚举值,用于指定查找时是否忽略大小写。例如:

string str = “Hello, World!”;int index = str.IndexOf(“world”, StringComparison.OrdinalIgnoreCase);Console.WriteLine(index);

在这个示例中,使用 OrdinalIgnoreCase 参数进行大小写不敏感的查找,输出结果为 7。

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