Skip to content

Instantly share code, notes, and snippets.

@abraham-ny
Created September 12, 2024 11:55
Show Gist options
  • Select an option

  • Save abraham-ny/26a40660cc5717dbd4e351029443b9e2 to your computer and use it in GitHub Desktop.

Select an option

Save abraham-ny/26a40660cc5717dbd4e351029443b9e2 to your computer and use it in GitHub Desktop.
Get Last Word In A String
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