当只有两个字符时,获取字符串中特定字符的第二个索引

dic*_*ğlu 1 .net c# vb.net

我需要获取字符串中特定字符的索引,但我需要知道它是否在该字符串中出现两次,如果是,则获取第二次出现的索引。我尝试了几件事,但找不到解决方案。有谁知道如何在 .Net 中完成?如果可能的话,vb.net。

我正在尝试的内容解释如下:

我有这样的字符串:01298461705691703

我需要在这个字符串中获取 17 的索引,但是如果字符串有两个 17,那么我需要知道第二个的索引。

Hay*_*tam 5

您将需要使用IndexOf两次,第二次使用其过载。

string myStr = "01298461705691703";

// Find the first occurence
int index1 = myStr.IndexOf("17");
// You might want to check if index1 isn't -1

// Find the second occurrence, starting from the previous one
int index2 = myStr.IndexOf("17", index1 + 1);
// We add +1 so that it doesn't give us the same index again
// Result will be 13
Run Code Online (Sandbox Code Playgroud)

请参阅:https : //docs.microsoft.com/en-us/dotnet/api/system.string.indexof