How do you use the indexOf method in Java?

The indexOf method in Java is used to find the first occurrence of a specified string within another string. Here is how it is used:

int indexOf(String str)

str is the string to be searched for.

Sample code:

String str = "hello world";
int index = str.indexOf("o");
System.out.println("第一次出现的位置:" + index);

The output result is:

第一次出现的位置:4

Note: The returned position is counted starting from 0, and if the string being searched for does not exist, then -1 will be returned.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds