温馨提示×

c# lastindexof 能查找非连续字符吗

c#
小樊
84
2024-11-24 00:07:34
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,IndexOf方法用于查找一个字符串在另一个字符串中首次出现的位置。它不能直接查找非连续字符,但你可以通过遍历字符串并使用IndexOf方法来查找非连续字符序列。

例如,假设你想查找字符串"hello"中的"l"字符,你可以使用以下代码:

string str = "hello";
char targetChar = 'l';
int index = 0;

while ((index = str.IndexOf(targetChar, index)) != -1)
{
    Console.WriteLine($"Found '{targetChar}' at position {index}");
    index++; // 移动到下一个字符,以便查找下一个匹配项
}

这将输出:

Found 'l' at position 2
Found 'l' at position 3

请注意,IndexOf方法在查找子字符串时也会返回非连续字符序列的位置。例如,str.IndexOf("ll")将返回2,因为"ll"子字符串从索引2开始。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c# lastindexof 如何忽略空格

0