Java Exercises: Find the length of last word of a specified string
Java Basic: Exercise-181 with Solution
Write a Java program to find the length of last word of a given string. The string contains upper/lower-case alphabets and empty space characters ' '.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
String str1 = "The length of last word";
System.out.println("Original String: "+str1);
System.out.println("Length of the last word of the above string: "+length_Of_last_word(str1));
}
public static int length_Of_last_word(String str1) {
int length_word = 0;
String[] words = str1.split(" ");
if(words.length>0) {
length_word = words[words.length-1].length();
} else {
length_word = 0;
}
return length_word;
}
}
Sample Output:
Original String: The length of last word Length of the last word of the above string: 4
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to swap every two adjacent nodes of a given linked list.
Next: Write a Java program to check if two binary trees are identical or not. Assume that two binary trees have the same structure and every identical position has the same value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework