学堂 学堂 学堂公众号手机端

C#中IndexOf和LastIndexOf方法如何使用

lewis 3年前 (2022-05-06) 阅读数 4 #技术

IndexOf和LastIndexOf方法都用于在字符串中查找特定字符或子字符串的位置。

IndexOf方法用于查找字符串中第一次出现特定字符或子字符串的位置,并返回该位置的索引值。如果未找到该字符或子字符串,则返回-1。

使用示例:


string str = "Hello, World!";
int index = str.IndexOf("o");
Console.WriteLine(index); // 输出结果为 4

LastIndexOf方法用于查找字符串中最后一次出现特定字符或子字符串的位置,并返回该位置的索引值。如果未找到该字符或子字符串,则返回-1。

使用示例:

string str = "Hello, World!";
int lastIndex = str.LastIndexOf("o");
Console.WriteLine(lastIndex); // 输出结果为 8
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门