C#中的String.IndexOf()方法用于在字符串中查找指定字符或子字符串的第一个匹配项,并返回其索引位置。该方法有多种重载形
C#中的String.IndexOf()方法用于在字符串中查找指定字符或子字符串的第一个匹配项,并返回其索引位置。该方法有多种重载形式,可以根据不同的需求使用。
以下是常见的使用方式:
1. 查找单个字符的索引位置:csharp
string str = "Hello World";
int index = str.IndexOf('o');
Console.WriteLine(index); // 输出:4
2. 查找子字符串的索引位置:csharp
string str = "Hello World";
int index = str.IndexOf("World");
Console.WriteLine(index); // 输出:6
3. 指定开始搜索的索引位置:csharp
string str = "Hello World";
int index = str.IndexOf('o', 5); // 从索引位置为5的字符开始搜索
Console.WriteLine(index); // 输出:7
4. 指定搜索的范围:csharp
string str = "Hello World";
int index = str.IndexOf("World", 0, 6); // 从索引位置为0到5的子字符串范围内搜索
Console.WriteLine(index); // 输出:-1,未找到匹配项
需要注意的是,如果未找到匹配项,则IndexOf()方法会返回-1。如果要查找多个匹配项的索引位置,可以使用循环结合IndexOf()方法进行迭代搜索。
--结束END--
本文标题: C# String.IndexOf()方法怎么使用
本文链接: https://www.lsjlt.com/news/431551.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-13
2024-05-13
2024-05-13
2024-05-13
2024-05-13
2024-05-13
2024-05-13
2024-05-13
2024-05-13
2024-05-13
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0