【C#】中IndexOf的用法

在 C# 中,IndexOf 方法是字符串和列表(如 List<T>)等数据结构中常用的方法,用于查找指定元素或子串首次出现的位置。以下是针对不同情况使用 IndexOf 的示例。

对于字符串

对于字符串类型,IndexOf 方法返回子字符串在原始字符串中的起始位置索引,如果没有找到则返回 -1。

基本用法如下:

cs 复制代码
string str = "Hello, world!";
int index = str.IndexOf("world"); // index 将会是 7

IndexOf 方法还有重载版本,可以接受额外参数:

  • startAt: 指定从字符串的哪个位置开始搜索。
  • count: 指定要搜索的字符数。
  • comparisonType: 指定比较时是否区分大小写。

示例:

cs 复制代码
string str = "Hello, hello!";
int index = str.IndexOf("hello", StringComparison.OrdinalIgnoreCase); // index 将会是 0
index = str.IndexOf("hello", 7, StringComparison.OrdinalIgnoreCase); // index 将会是 7

对于 List<T>

对于 List<T> 类型,IndexOf 方法返回指定元素在列表中的索引,如果列表中不包含该元素,则返回 -1。

基本用法如下:

cs 复制代码
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int index = numbers.IndexOf(3); // index 将会是 2

如果列表中的元素类型是引用类型,你可以传递任何与列表元素类型兼容的对象给 IndexOf 方法。

完整示例代码

下面是一个完整的示例程序,演示了如何使用 IndexOf 方法:

cs 复制代码
using System;

class Program
{
    static void Main()
    {
        string text = "Welcome to the C# programming language.";
        
        Console.WriteLine("Index of 'C#': " + text.IndexOf("C#")); // 输出: Index of 'C#': 16
        
        List<string> languages = new List<string> { "Java", "C#", "Python", "JavaScript" };
        
        Console.WriteLine("Index of 'C#': " + languages.IndexOf("C#")); // 输出: Index of 'C#': 1
    }
}

List<T>相关链接

【C# 】 一个List<T> 如何快速的知道里面的最大、最小、平均值呢?_c#获取list集合中的最大最小值-CSDN博客文章浏览阅读296次。【C# 】 一个List 如何快速的知道里面的最大、最小、平均值呢?_c#获取list集合中的最大最小值https://blog.csdn.net/wangnaisheng/article/details/140514960

C# 快速把List<string>集合转换成一个字符串_list 转字符串-CSDN博客文章浏览阅读892次。C# 快速把List集合转换成一个字符串_list 转字符串https://blog.csdn.net/wangnaisheng/article/details/138717158

C# 对List<T>取交集、差集以及并集-CSDN博客文章浏览阅读2.5k次。C# 对List取交集、差集以及并集https://blog.csdn.net/wangnaisheng/article/details/131391464

相关推荐
samble3 小时前
从零搭建灌装监控系统(十七):LiveCharts 实时温度曲线
c#·wpf·mvvm·modbus·工业控制
淡海水12 小时前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间
小羊没烦恼!14 小时前
OS X 上使用.NET开发应用程序
开发语言·前端·数据库·人工智能·c#·策略模式
Behavior15 小时前
Unity 7.0 Alpha 拆解:编辑器干掉 Mono 换 CoreCLR
c#·unity3d·游戏开发
淡海水16 小时前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量
Vertira16 小时前
C# 函数封装成 DLL,
开发语言·c#
浅尝辄止;18 小时前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#
kimloner1 天前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)
windows·开源·c#·ocr·winforms
阿松爱学习1 天前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
半亩码田1 天前
C#转Python第4.8篇:正则表达式:Python re 模块 vs C# System.Text.RegularExpressions
python·正则表达式·c#