+ 1

How to get the last word from a text?

Well I have to count the times that one word appear in a text. Each word is between one space. But my code doesnt count the last word. I dont know how to do it. Language : java. Any advice? I thought to get the last space and take that position + 1 to the length but It doesnt worked :(

5th Feb 2018, 2:09 AM
Miguel MartĂ­nez
Miguel MartĂ­nez - avatar
4 Answers
+ 3
String str = "one two three four five six seven eight nine"; // If you know the last word int idx = str.indexOf("nine"); System.out.println(str.substring(idx)); // If you know or not the last word String[] words = str.split("\\s+"); System.out.println(words[words.length - 1]); You should use the array variant, like that: String str = "w1 w4 w2 w1 w5 w3 w1"; String matchWord = "w1"; String[] words = str.split("\\s+"); int count = 0; // Iterating to the last element // Or use 'for each' loop for simplicity for (int i = 0; i < words.length; i++) { if (words[i].equals(matchWord)) { count++; } } System.out.printf("The word %s is found %d times.\n", matchWord, count);
5th Feb 2018, 3:12 AM
Boris Batinkov
Boris Batinkov - avatar
+ 2
Thank you all! :D
5th Feb 2018, 9:53 PM
Miguel MartĂ­nez
Miguel MartĂ­nez - avatar
+ 1
https://code.sololearn.com/cLw9lKqX4U7m/?ref=app split the text into an array and then get the final index.. use the length and then -1 because arrays start at 0
5th Feb 2018, 2:35 AM
LordHill
LordHill - avatar
0
I literally have no idea. I was about to post it in css...then i saw "Language: java" in your text and i was all like,"Well @#$*". No worries, you should use a scanner then use .length at the end of the array. That is all I know. Sorry...hope this helped.
5th Feb 2018, 2:40 AM
Someone Else
Someone Else - avatar