This should print the list of positions without the -1 at the end that Peter Lawrey's solution has had.

int index = word.indexOf(guess);
while (index >= 0) {
    System.out.println(index);
    index = word.indexOf(guess, index + 1);
}

It can also be done as a for loop:

for (int index = word.indexOf(guess);
     index >= 0;
     index = word.indexOf(guess, index + 1))
{
    System.out.println(index);
}

[Note: if guess can be longer than a single character, then it is possible, by analyzing the guess string, to loop through word faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]

Answer from Ted Hopp on Stack Overflow
🌐
Reddit
reddit.com › r/learnjava › find all index of occurrences of character in a string
r/learnjava on Reddit: Find all index of occurrences of character in a string
October 7, 2024 -

https://books.google.com.np/books?id=h0Uhz4lBoF8C&pg=PA172&dq=find+index+of++occurrences+character+in+a+string&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwjI-qzhp_uIAxX5S2wGHUHiL_MQ6AF6BAgGEAI#v=onepage&q&f=false

I found this solution here and re-wrote my code for it. And it works. And I was also attempting to use similar logic. However, I don't really grasp it by heart till of now. I am not able to internalize it.

if (wordToGuess.contains(userGuess)) {
                int aIndex = -1;
                while ((aIndex = wordToGuess.indexOf(userGuess, ++aIndex)) > -1) {
                    indexArr[aIndex] = 1;
                }
                displayAsterik(indexArr, wordToGuess);
            } else {
                mistakes = mistakes + 1;
            }

This is the code, the while loop is the part I am failing to analyze. I can obviously trace this loop with each input and see it works. However, the bigger question is designing such solutions in which cases in the future.

Top answer
1 of 5
7
Why would you even need the indexOf method? The naive, straightforward approach is to use .charAt and to loop over the characters in the string using a forloop. (TBH, .indexOf does exactly the same under the hood, just adds a starting index and it stops on the first occurrence). Honestly, the only way to learn proper programming is to stop searching for solutions and to sit down and try to work out your own solutions, because otherwise, you get in over your head, as in your case ending with code that you might have been able to somewhat reproduce, but that you don't understand. Start with pen(cil) and paper and try to figure out how you, the person, would address a problem. Only once you have found a solution start thinking about programming it. And don't memorize. Especially not code. Code adapts to the situation and is only the end product, not the starting point. Edit: Very mature move/s of you blocking people that offer help and advice to you just because you feel personally attacked or disagree with what has been said.
2 of 5
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Discussions

List all index of all characters in a string in Java 8 - Stack Overflow
Given a string want a map of list where the key will be each character and value will be a list of integers indicating indexes where the character is present.\ I want to do it in Java 8 Input: stan... More on stackoverflow.com
🌐 stackoverflow.com
java - indexOf to find all occurrences of a word in a String - Stack Overflow
I'm trying to use indexOf to find all occurrences of the characters 'the' in a sentence. For example, if the sentence were "The other day I went over there", it should return 3. I am able to do t... More on stackoverflow.com
🌐 stackoverflow.com
July 28, 2016
java - Get string character by index - Stack Overflow
I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the nth position? So in the string "foo", if I More on stackoverflow.com
🌐 stackoverflow.com
Find all index of occurrences of character in a string
Why would you even need the indexOf method? The naive, straightforward approach is to use .charAt and to loop over the characters in the string using a forloop. (TBH, .indexOf does exactly the same under the hood, just adds a starting index and it stops on the first occurrence). Honestly, the only way to learn proper programming is to stop searching for solutions and to sit down and try to work out your own solutions, because otherwise, you get in over your head, as in your case ending with code that you might have been able to somewhat reproduce, but that you don't understand. Start with pen(cil) and paper and try to figure out how you, the person, would address a problem. Only once you have found a solution start thinking about programming it. And don't memorize. Especially not code. Code adapts to the situation and is only the end product, not the starting point. Edit: Very mature move/s of you blocking people that offer help and advice to you just because you feel personally attacked or disagree with what has been said. More on reddit.com
🌐 r/learnjava
10
3
October 7, 2024
🌐
CodingTechRoom
codingtechroom.com › question › get-all-indexes-character-string-java
How to Find All Occurrences of a Character in a String in Java - CodingTechRoom
import java.util.ArrayList; import java.util.List; public class CharacterIndexes { public static void main(String[] args) { String word = "bannanas"; String guess = "n"; List<Integer> indexes = new ArrayList<>(); for (int i = 0; i < word.length(); i++) { if (String.valueOf(word.charAt(i)).equals(guess)) { indexes.add(i); } } System.out.println(indexes); // Output: [2, 3, 5] } }
🌐
javathinking
javathinking.com › blog › indexes-of-all-occurrences-of-character-in-a-string
Java: How to Find All Indexes of a Character in a String (Example: Get [2,3,5] for 'n' in 'bannanas') — javathinking.com
Iterate over each character in the string (using loops or streams). For each character, check if it matches the target. If it matches, add its index to the collection. Return the collection of indexes. Below are four practical methods to implement this logic, ranging from basic loops to modern Java 8+ features.
🌐
YouTube
youtube.com › watch
How to find index of a character or string in java? - YouTube
#learnwithkrishnasandeep #javacodinginterviewquestions #javaexamples #javaprograms #javatutorials #javaprogramming get character index string java,find ind...
Published   March 31, 2016
🌐
Baeldung
baeldung.com › home › java › java string › using indexof to find all occurrences of a word in a string
Using indexOf to Find All Occurrences of a Word in a String | Baeldung
January 8, 2024 - In any context, the search is so well-known and daunting a chore that it is popularly called the “Needle in a Haystack Problem”. In this tutorial, we’ll demonstrate a simple algorithm that uses the indexOf(String str, int fromIndex) method of ...
🌐
CodeGym
codegym.cc › java blog › strings in java › java string indexof()
Java String indexOf()
December 26, 2024 - Found 'a' at position: 1 Found ... programming language. Java is widely used in web development" and then used the indexOf() method to find all occurrences of the character 'a' or the substring "Java" in the str...
🌐
Tutorial Gateway
tutorialgateway.org › java-program-to-find-all-occurrences-of-a-character-in-a-string
Java Program to Find All Occurrences of a Character in a String
December 20, 2024 - If True, we print that character along with position (not the index position). If you want the extract index position, please replace i + 1 with i. import java.util.Scanner; public class FindAllCharOccurence1 { private static Scanner sc; public static void main(String[] args) { String facStr; char ch; int i = 0; sc= new Scanner(System.in); System.out.print("\nPlease Enter any String = "); facStr = sc.nextLine(); System.out.print("\nEnter the Character to Find = "); ch = sc.next().charAt(0); while(i < facStr.length()) { if(facStr.charAt(i) == ch) { System.out.format("\n %c Found at Position %d ", ch, i + 1); } i++; } } }
Find elsewhere
🌐
Javatpoint
javatpoint.com › java-string-indexof
Java String.indexOf()
Java String indexOf() method with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string indexof in java etc.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › find-indices-of-all-occurrence-of-one-string-in-other
Print all occurrences of a string as a substring in another string - GeeksforGeeks
July 11, 2025 - A simple solution is to check all substrings of a given string one by one. If a substring matches print its index. ... // Java program to find indices of all // occurrences of one String in other.
🌐
iO Flood
ioflood.com › blog › indexof-java
Java's String IndexOf Method: A Detailed Usage Guide
February 26, 2024 - Many developers find themselves in a similar situation, but there’s a method in Java that can make this task straightforward. Think of Java’s indexOf() method as a detective – it can help you pinpoint the exact position of your target ...
🌐
freeCodeCamp
freecodecamp.org › news › indexof-in-java-how-to-find-the-index-of-a-string-in-java
indexOf in Java – How to Find the Index of a String in Java
March 24, 2022 - 7 is returned as the index of the second "o" character. In the next example, we'll understand how the public int indexOf(String str) method which returns the index of a substring works.
🌐
W3Schools
w3schools.com › java › ref_string_indexof.asp
Java String indexOf() Method
Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum
🌐
Software Testing Help
softwaretestinghelp.com › home › java › java string indexof method with code examples
Java String indexOf Method With Syntax & Code Examples
April 1, 2025 - We have already discussed the first ... for the character index has to be started. This is the simplest form of the Java indexOf() method....
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › indexOf
Java String indexOf() - Find Character Index | Vultr Docs
December 17, 2024 - It effectively prints all starting positions of "Java" in the string. The indexOf() function in Java is a versatile tool that helps you detect the position of characters or substrings within strings.