0
Index of an Element in String Java
Hello SoloLearn friends! I am trying to return the position/index for a word in a sentence. In my code below, I get the positon/index one less than the correct number. For example, for sentence "I like listening to music!", correct position for "music" is 5 but my program returns 4. Any suggestions? Thanks! public class Challenge { public static String findWord(String sentence) { String[] strArray = sentence.split(" "); for (int i = 1; i < strArray.length; i++){ if (strArray[i].equals("music")) return "I found music at " + i + "!"; }return "I can't find music"; } }
4 odpowiedzi
+ 3
GE12 if you write i = 1 in for loop it doesn't mean that position will change.
i = 1 means 2nd position in Java
i = 0 means 1st position
See the Example:
https://code.sololearn.com/cfr0AV7mOUIL/?ref=app
+ 2
GE12 Index start from 0 in Java. So music is on 4th position.
To get 5 just print i + 1 instead of i
+ 1
Thanks for the code example AJ Anant.
Adding +1 to i in the return statement worked!
0
@AJ Anant Unfortunately I get the same results (in test cases) with index from 0 :(