Java: method to get position of a match in a String?
To get the position of a match in a String
in Java, you can use the indexOf()
method of the String
class.
The indexOf()
method returns the index of the first occurrence of a specified character or substring in the string. If the character or substring is not found, it returns -1.
Here is an example of how you can use the indexOf()
method to get the position of a match in a String
:
String s = "Hello, World!";
int index = s.indexOf("World"); // index is 7
In this example, the indexOf()
method returns the index of the first occurrence of the substring "World" in the string s
. The index is 7, because "World" starts at the 8th character of the string (index 7).
You can also use the lastIndexOf()
method to get the index of the last occurrence of a character or substring in the string.
I hope this helps! Let me know if you have any questions.