user2786737 user2786737 - 2 months ago 6
Java Question

Find position of a substring in a string(not indexOf)

ex

String str = "abc def ghi";


Is there any method like
str.find("abc")
will return me 1
and
str.find("def")
will return me 2?

java language..

Answer

How about something like this?

int getIndex(String str, String substring)
{
  return Arrays.asList(str.split("\\s+")).indexOf(substring)+1;
}

Disclaimer: This isn't at all efficient. It splits the whole string from scratch every time the function is called.

Test code:

String str = "abc def ghi";
System.out.println(getIndex(str, "abc"));
System.out.println(getIndex(str, "def"));

Prints:

1
2

Explanation:

str.split("\\s+") splits the string by white-space and puts each part into a position in an array.

Arrays.asList returns an ArrayList for the array.

indexOf(substring) finds the position of the string in the ArrayList.

+1 since Java uses 0-indexing and you want 1-indexing.