How to find the position of a string in Java?
In Java, you can use the indexOf() method of the String class to find the position of a string. The syntax of this method is as follows:
int indexOf(String str)
In this method, “str” is the string being searched for. The function will return the position of the first occurrence of the string, or -1 if the string is not found.
For example, to find the position of the characters “World” in the string “Hello World”, you can use the following code:
String str = "Hello World";
int position = str.indexOf("World");
System.out.println("位置:" + position);
The output result is:
位置:6
Moreover, there is another overloaded version of the indexOf() method that allows you to specify the starting position to search for the string. For example:
String str = "Hello World";
int position = str.indexOf("o", 5);
System.out.println("位置:" + position);
The output result is:
位置:7
The code searches for the character “o” starting from the 5th position, not from the beginning of the string.