What is the simplest way to get the last word of a string in Java? You can assume no punctuation (just alphabetic characters and whitespace).
To get the last word of a string: Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.
If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str.
Java String trim() Method The trim() method removes whitespace from both ends of a string.
String test = "This is a sentence"; String lastWord = test.substring(test.lastIndexOf(" ")+1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With