how to find Length of Last Word in the given string using java?

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0. **

‘I am getting wrong answer as output Your input “Hello World” Output 1 Expected 5’

** here is my solution
class Solution { public int lengthOfLastWord(String s) { if(s.length()==0) { return 0; } String words[]=null; words=s.split(""); String str=words[words.length-1]; return str.length(); } }

Answer

try this, here yo can get last word from string:

if (s == null || s.length() == 0) {
    return 0;
} else {
    String lastWord = s.substring(s.lastIndexOf(" ") + 1);
    return lastWord.length();
}

Leave a Reply

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