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 的重载版本可以提供更多的灵活性,如指定搜索范围和比较类型。
相关推荐
2301_800976931 分钟前
正则表达式
开发语言·python·正则表达式
故事还在继续吗6 分钟前
C++20关键特性
开发语言·c++·c++20
青少儿编程课堂43 分钟前
2026青少儿信息素养大赛备赛指南!Python/Scratch/C++备考要点
开发语言·c++·python
程序设计实验室1 小时前
Spark.NET:一个试图把 Django / Rails 式开发体验带回 .NET 世界的全栈 Web 框架。
c#
AIFarmer1 小时前
【无标题】
开发语言·c++·算法
昇腾CANN2 小时前
TileLang-Ascend 算子性能优化方法与实操
开发语言·javascript·性能优化·昇腾·cann
沐知全栈开发2 小时前
ionic 手势事件详解
开发语言
lsx2024062 小时前
Bootstrap 按钮
开发语言
神仙别闹2 小时前
基于 Python 实现 BERT 的情感分析模型
开发语言·python·bert
一曦的后花园2 小时前
linux搭建promethes并对接node-exporter指标
linux·运维·服务器