DEV Community

Vasanth S
Vasanth S

Posted on

Practice Program in java Day-10

Today I learned the new topic of String:
find the length of last word in a string;

program :
class Solution {
public int lengthOfLastWord(String s) {
int last = s.length() - 1;

    while (last >= 0 && s.charAt(last) == ' ') {//to remove he spaces
        last--;
    }

    int start = last;
    while (start >= 0 && s.charAt(start) != ' ') {
        start--;
    }

    return last - start;        
}
public static void main(String... args){
    String a="fly of moon ";
    int S=lengthOfLastWlrd(a);
    System.out.println(S);}
Enter fullscreen mode Exit fullscreen mode

}
}

Top comments (0)