You can use string.indexOf('a').
If the char a is present in string :
Answer from mP. on Stack Overflowit returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
You can use string.indexOf('a').
If the char a is present in string :
it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
String.contains()which checks if the string contains a specified sequence of char valuesString.indexOf()which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
Find all index of occurrences of character in a string
[JAVA] Best practice to obtain substring using index of a character that may not be in original string.
[homework java] I don't know how to replace string using the indexOf method
Java why i cant check if string contains char?
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.