Created
September 12, 2024 11:55
-
-
Save abraham-ny/26a40660cc5717dbd4e351029443b9e2 to your computer and use it in GitHub Desktop.
Get Last Word In A String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class LastWordExtractor { | |
| public static String getLastWord(String input) { | |
| // Trim the input string to remove leading and trailing whitespaces | |
| input = input.trim(); | |
| // Find the index of the last space character | |
| int lastIndex = input.lastIndexOf(' '); | |
| // Check if a space was found | |
| if (lastIndex != -1) { | |
| // Use substring to extract the last word | |
| return input.substring(lastIndex + 1); | |
| } else { | |
| // If there are no spaces, the entire string is the last word | |
| return input; | |
| } | |
| } | |
| public static void main(String[] args) { | |
| String input1 = "Hello World"; | |
| String input2 = " This is a test "; | |
| String input3 = "Java"; | |
| System.out.println("Last word of '" + input1 + "': " + getLastWord(input1)); | |
| System.out.println("Last word of '" + input2 + "': " + getLastWord(input2)); | |
| System.out.println("Last word of '" + input3 + "': " + getLastWord(input3)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment