📅  最后修改于: 2023-12-03 14:42:14.516000             🧑  作者: Mango
As a Java developer, you may have come across the need to find all occurrences of a specific character or string in a given string. This can be achieved using the indexOf()
method in Java. In this guide, we will explore how to find all occurrences of a string using indexOf()
and other related methods.
The basic syntax of indexOf()
method in Java is as follows:
int indexOf(int ch)
int indexOf(int ch, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndex)
int indexOf(int ch)
This method returns the index of the first occurrence of the given character in the string. If the character is not found, it returns -1.
String str = "hello world";
int index = str.indexOf('o');
// index will be 4
int indexOf(int ch, int fromIndex)
This method returns the index of the first occurrence of the given character in the string, starting from the specified index. If the character is not found, it returns -1.
String str = "hello world";
int index = str.indexOf('o', 5);
// index will be 7
int indexOf(String str)
This method returns the index of the first occurrence of the given string in the original string. If the string is not found, it returns -1.
String str = "hello world";
int index = str.indexOf("world");
// index will be 6
int indexOf(String str, int fromIndex)
This method returns the index of the first occurrence of the given string in the original string, starting from the specified index. If the string is not found, it returns -1.
String str = "hello world";
int index = str.indexOf("o", 5);
// index will be 7
If you want to find all occurrences of a string in the original string, you can use a loop in conjunction with the indexOf()
method to achieve this. Here's an example:
String str = "hello world";
String searchStr = "l";
int index = str.indexOf(searchStr);
while (index >= 0) {
System.out.println(index);
index = str.indexOf(searchStr, index + 1);
}
Output:
2
3
9
Finding all occurrences of a string can be easily achieved using the indexOf()
method in Java. We hope this guide has been helpful in explaining the different variations of indexOf()
and how to use them to your advantage. Enjoy coding in Java!