Knowee
Questions
Features
Study Tools

How to find all occurrences of a character or substring in Strings in Java?

Question

How to find all occurrences of a character or substring in Strings in Java?

🧐 Not the exact question you are looking for?Go ask a question

Solution

To find all occurrences of a character or substring in a String in Java, you can use the indexOf() method in a loop. Here's a step-by-step guide:

  1. Define the string and the character or substring you want to find.
String str = "This is a sample string";
String subStr = "is";
  1. Initialize a variable to store the index position. Set it to 0 initially.
int index = 0;
  1. Use a while loop to find the substring. Inside the loop, use the indexOf() method to find the substring. The indexOf() method takes two parameters: the substring to find and the index to start the search from.
while ((index = str.indexOf(subStr, index)) != -1) {
    System.out.println("Substring found at index: " + index);
    index += subStr.length();
}

In this loop, indexOf() will return -1 if it doesn't find the substring. If it finds the substring, it will return the starting index of the substring. We print this index, then increment the index by the length of the substring to search for the next occurrence.

This will print all the index positions of the substring in the string.

This problem has been solved

Similar Questions

Write a program to find the substring of a given string.

How do you find the non-matching characters in a string?

How can you find out if a sub-string is present in a given string?myString.includes(subString)myString.find(subString)myString.has(subString)

Write a Java program to check whether a substring(abc) appears before a period(.) within a given string

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace() .

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.