Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Simplest way to get last word in a string

Tags:

java

string

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).

like image 979
Muhd Avatar asked Jan 12 '11 18:01

Muhd


People also ask

How do I get the last word in a string?

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.

How do you get the last letter of a string in Java?

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.

What is TRIM () in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string.


1 Answers

String test =  "This is a sentence"; String lastWord = test.substring(test.lastIndexOf(" ")+1); 
like image 199
OscarRyz Avatar answered Sep 24 '22 15:09

OscarRyz