news 2026/6/23 21:12:56

C#:string.IndexOf

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C#:string.IndexOf

在 C# 中,字符串(string)的 IndexOf 方法用于查找子字符串在原始字符串中的位置。值得注意的是,字符串的索引是从 0 开始的,这意味着第一个字符的索引是 0,第二个字符的索引是 1,以此类推。
1、IndexOf 方法的基本使用

‌查找子字符串的第一次出现的位置‌
string originalString = "Hello, World!";
int index = originalString.IndexOf("World");
Console.WriteLine(index); // 输出 7

这里,IndexOf 方法返回子字符串 "World" 在原始字符串中的起始位置的索引,即 7。

2、 ‌查找子字符串的最后一次出现的位置‌
string originalString = "test test test";
int index = originalString.LastIndexOf("test");
Console.WriteLine(index); // 输出 10

这里使用了 LastIndexOf 方法来找到最后一次出现的位置。

‌3、查找子字符串的指定位置之后第一次出现的位置‌
string originalString = "Hello, World!";
int startIndex = 7; // 从索引7开始搜索(即"World"后面的位置)
int index = originalString.IndexOf("!", startIndex);
Console.WriteLine(index); // 输出 12,即在"World!"之后的感叹号的位置

这里从索引 7 开始搜索感叹号 "!" 的位置。

4、IndexOf 方法的高级用法

‌(1)忽略大小写‌
string originalString = "Hello, World!";
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase;
int index = originalString.IndexOf("world", comparisonType);
Console.WriteLine(index); // 输出 7,即使不匹配大小写

使用 StringComparison 枚举可以指定搜索时是否忽略大小写。

‌(2)查找子字符串的索引范围‌
string originalString = "Hello, World!";
int startIndex = 0; // 开始搜索的位置
int count = originalString.Length; // 搜索的范围长度
int index = originalString.IndexOf("World", startIndex, count, StringComparison.Ordinal);
Console.WriteLine(index); // 输出 7

通过指定 startIndex 和 count,可以限制搜索的范围。

5、注意事项

  • 如果子字符串不存在于原始字符串中,IndexOf 方法将返回 -1
  • 当使用 LastIndexOf 方法时,如果从指定的开始位置向后查找,也可以指定搜索范围。
  • 使用 IndexOf 和 LastIndexOf 的重载版本可以提供更多的灵活性,如指定搜索范围和比较类型。
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/23 13:30:19

Steamless终极指南:轻松移除Steam游戏DRM保护

Steamless终极指南:轻松移除Steam游戏DRM保护 【免费下载链接】Steamless Steamless is a DRM remover of the SteamStub variants. The goal of Steamless is to make a single solution for unpacking all Steam DRM-packed files. Steamless aims to support as …

作者头像 李华
网站建设 2026/6/23 19:08:37

图像对比工具在网络安全配置中的高效应用与优化策略

图像对比工具在网络安全配置中的高效应用与优化策略 【免费下载链接】image-compare-viewer Compare before and after images, for grading and other retouching for instance. Vanilla JS, zero dependencies. 项目地址: https://gitcode.com/gh_mirrors/im/image-compare…

作者头像 李华
网站建设 2026/6/23 20:26:18

终极指南:macOS iSCSI Initiator快速连接远程存储

终极指南:macOS iSCSI Initiator快速连接远程存储 【免费下载链接】iSCSIInitiator iSCSI Initiator for macOS 项目地址: https://gitcode.com/gh_mirrors/is/iSCSIInitiator macOS iSCSI Initiator是一款功能强大的开源软件,专门为苹果电脑用户…

作者头像 李华
网站建设 2026/6/23 11:49:03

FastDepth:嵌入式系统上的快速单目深度估计

FastDepth:嵌入式系统上的快速单目深度估计 【免费下载链接】fast-depth ICRA 2019 "FastDepth: Fast Monocular Depth Estimation on Embedded Systems" 项目地址: https://gitcode.com/gh_mirrors/fa/fast-depth FastDepth 是一个专门为嵌入式系…

作者头像 李华