1

I need to get the index of a specific character in a string, but I need to know if it occurs twice in that string and if it is so, get the second occurrence index. I tried a few things but couldn't find the solution. Does anyone know how can it be done in .Net? Vb.net if possible.

What I am trying is explained below:

I have string like : 01298461705691703

I need to aquire the index of 17 in this string but if the string has two 17's then I need to know the index of the second one.

  • 1
    .IndexOf() will give you the position of the 1st occurrence, you can then use .IndexOf() again to look after that position for a 2nd occurrence. – Alex K. Apr 10 '19 at 11:06
  • So basically you want the index of the last occurrence?? I mean if you have 3 occurrences, you still want the second one? Or the last one? – Mohamad Mousheimish Apr 10 '19 at 11:13
  • Possible duplicate of [How to get the Index of second comma in a string](https://stackoverflow.com/questions/22669044/how-to-get-the-index-of-second-comma-in-a-string) – MatSnow Apr 10 '19 at 11:27

3 Answers3

5

You will need to use IndexOf two times, using its overload on the second time.

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

See: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof

Haytam
  • 4,643
  • 2
  • 20
  • 43
2

Start your string from first occurrence 17, something similar to

    string str = "01298461705691703";
    int i = str.IndexOf("17", s.IndexOf("17")+1);
                            //^^^^^^^^^^^^^^^^^ This will start your string from first occurrence of 17     

Syntax of indexOf

string.IndexOf(Char, Int32)

where,

  • char is a unicode character to seek.

  • Int32 is starting index of string


If you are trying to find out last occurrence of 17 in string, then you can use string.LastIndexOf() method.

    string str = "01298461705691703";
    int lastIndex = str.LastIndexOf("17");

POC : .Net Fiddle

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
1

The solution is String.LastIndexOf

Dim myStr as String = "01298461705691703"
Dim idx as Integer = myStr.LastIndexOf("17")

or in c#

string myStr = "01298461705691703";
int idx = myStr.LastIndexOf("17");
IvanH
  • 5,039
  • 14
  • 60
  • 81