我需要获取字符串中特定字符的索引,但是我需要知道它在该字符串中是否出现两次,如果是,请获取第二个出现索引。 我尝试了一些尝试,但找不到解决方案。有谁知道如何在.Net中完成? Vb.net。
我正在尝试的解释如下:
我有这样的字符串:01298461705691703
我需要获取此字符串中的索引17,但是如果字符串中有两个17,则我需要知道第二个索引。
答案 0 :(得分:4)
您将需要使用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
请参阅:https://docs.microsoft.com/en-us/dotnet/api/system.string.indexof
答案 1 :(得分:0)
从第一次出现17
开始,类似于
string str = "01298461705691703";
int i = str.IndexOf("17", s.IndexOf("17")+1);
//^^^^^^^^^^^^^^^^^ This will start your string from first occurrence of 17
indexOf的语法
哪里
char 是要查找的Unicode字符。
Int32 是字符串的起始索引
如果您尝试找出字符串中17
的最后一次出现,则可以使用string.LastIndexOf()
方法。
string str = "01298461705691703";
int lastIndex = str.LastIndexOf("17");
POC:.Net Fiddle
答案 2 :(得分:0)
解决方案是String.LastIndexOf
Dim myStr as String = "01298461705691703"
Dim idx as Integer = myStr.LastIndexOf("17")
或在c#
中string myStr = "01298461705691703";
int idx = myStr.LastIndexOf("17");