[SOLVED] How to obtain the length of the last word in the string


I have reversed the string and have a for loop to iterate through the reversed string.

I am counting characters and I know I have a logic flaw, but I cannot pinpoint why I am having this issue.

The solution needs to return the length of the last word in the string.

My first thought was to iterate through the string backward (I don’t know why I decided to create a new string, I should have just iterated through it by decrementing my for loop from the end of the string).

But the logic should be the same from that point for my second for loop.

My logic is basically to try to count characters that aren’t whitespace in the last word, and then when the count variable has a value, as well as the next whitespace after the count has counted the characters of the last word.

class Solution {
    public int lengthOfLastWord(String s) {
        int count = 0;
        int countWhite = 0;
        char ch;
        String reversed = "";
        for(int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            reversed += ch;
        for(int i = 0; i < reversed.length(); i++) {
            if(!Character.isWhitespace(reversed.charAt(i))) {
                if(count > 1 && Character.isWhitespace(reversed.charAt(i)) == true) {
        return count;


Maybe try this,

public int lengthOfLastWord(String s) {
String [] arr = s.trim().split(" ");

return arr[arr.length-1].length();


Answered By – Shubham Saraswat

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *