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.]
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.]
Try the following (Which does not print -1 at the end now!)
int index = word.indexOf(guess);
while(index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index+1);
}
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.
List all index of all characters in a string in Java 8 - Stack Overflow
java - indexOf to find all occurrences of a word in a String - Stack Overflow
java - Get string character by index - Stack Overflow
Find all index of occurrences of character in a string
A neat trick you can use is to stream the indices of the string, and then collect them by the character at that index:
Map<Character, List<Integer>> indices =
IntStream.range(0, input.length())
.boxed()
.collect(Collectors.groupingBy(input::charAt));
In order to keep the order of insertion, a LinkedHashMap has to be used when grouping the indexes by character:
String input = "standard";
Map<Character, List<Integer>> charIndexes =
IntStream.range(0, input.length())
.boxed()
.collect(Collectors.groupingBy(
input::charAt, LinkedHashMap::new, Collectors.toList()
));
Similar solution without using Stream API:
Map<Character, List<Integer>> charIndexes = new LinkedHashMap<>();
for (int i = 0, n = input.length(); i < n; i++) {
charIndexes.computeIfAbsent(input.charAt(i), k -> new ArrayList<>()).add(i);
}
Then the contents of the map may be printed like this:
charIndexes.forEach((c, ix) -> System.out.println(
c + " - " + ix.stream().map(String::valueOf).collect(Collectors.joining(","))
));
Output
s - 0
t - 1
a - 2,5
n - 3
d - 4,7
r - 6
You can keep track of the index:
int index = theString.indexOf("the");
while(index >= 0) {
index = theString.indexOf("the", index+1);
counter2++;
}
You have taken a complicated approach. Try this:
int count = str.split("the", -1).length - 1;
If you absolutely must use indexOf():
str = str.toLowerCase();
int count = 0;
for (int i = str.indexOf("the"); i >= 0; i = str.indexOf("the", i + 1))
count++;
The method you're looking for is charAt. Here's an example:
String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
For more information, see the Java documentation on String.charAt. If you want another simple tutorial, this one or this one.
If you don't want the result as a char data type, but rather as a string, you would use the Character.toString method:
String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
If you want more information on the Character class and the toString method, I pulled my info from the documentation on Character.toString.
You want .charAt()
Here's a tutorial
"mystring".charAt(2)
returns s
If you're hellbent on having a string there are a couple of ways to convert a char to a string:
String mychar = Character.toString("mystring".charAt(2));
Or
String mychar = ""+"mystring".charAt(2);
Or even
String mychar = String.valueOf("mystring".charAt(2));
For example.