c# " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2024-04-29 09:20:40
c#

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

扫码添加客服微信