Get the Last Word of a String

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

How to find the last word in a string

String#lastIndexOf and String#substring are your friends here.

chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.

String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));

This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.

String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));

If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.

String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);

How to extract the first and final words from a string?

You have to firstly convert the string to list of words using str.split and then you may access it like:

>>> my_str = "Hello SO user, How are you"
>>> word_list = my_str.split() # list of words

# first word v v last word
>>> word_list[0], word_list[-1]
('Hello', 'you')

From Python 3.x, you may simply do:

>>> first, *middle, last = my_str.split()

Get the last word of string

For this case, you can first trim the string:

String s = "hello is my new car ".trim();

Trim removes all trailing and leading spaces.

Then you can split the String like:

String[] words = s.split(" ");

Once you have that you can simply get the last index which will be the last word:

String lastWord = words[words.length - 1];

Ofcourse, for more complex issues regex would be a better option.

UPDATE:

In order to remove this word from the string you can simply replace it:

String withoutWord = s.replace(lastWord, "");

How to find the last word in a String in Java?

Here is my code:

myString = myString.trim();
String[] wordList = myString.split("\\s+");
System.out.println(wordList[wordList.length-1]);

How to obtain the length of the last word in the string

Maybe try this,

public int lengthOfLastWord(String s) {

String [] arr = s.trim().split(" ");

return arr[arr.length-1].length();

}

How to get last word name from a string

Use String#split method to split based on delimiter / and get the last element of the array using Array#pop method.

var text = 'http://xxx:9696/images/FSDefault.jpg';
console.log(text.split('/').pop())

obtain last word from a string in python

Using re.findall for a regex option, we can try:

inp = 'UPPER(\"Sales\".\"PRODUCTS\".\"PRODUCT_NAME\" )'
output = re.findall(r'^.*\b(\w+).*$', inp)
print(output[0]) # prints PRODUCT_NAME

For an explanation of how this works, the regex pattern will match everything up to the final word boundary, followed by the final word. We then access this match to print the result you want.

Javascript: Returning the last word in a string

Try this:

you can use words with n word length.

example:

  words = "Hello World";
words = "One Hello World";
words = "Two Hello World";
words = "Three Hello World";

All will return same value: "World"

function test(words) {
var n = words.split(" ");
return n[n.length - 1];

}

Find the length of last word of a string without using string methods - Python

Assuming you don't care about punctuation, how about just iterating from the back of the string to:

  1. Find the first non-whitespace character:
  2. Find the first whitespace character before the above character:

Note: Calling len on a string is O(1).

# Source: https://github.com/python/cpython/blob/738c19f4c5475da186de03e966bd6648e5ced4c4/Objects/unicodetype_db.h#L6151
UNICODE_WHITESPACE_CHARS = {0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C,
0x001D, 0x001E, 0x001F, 0x0020, 0x0085, 0x00A0,
0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004,
0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
0x2028, 0x2029, 0x202F, 0x205F, 0x3000}

def get_last_non_whitespace_index(sentence: str) -> int:
sentence_length = len(sentence)
i = sentence_length - 1
while i >= 0:
if ord(sentence[i]) not in UNICODE_WHITESPACE_CHARS:
return i
i -= 1
return -1

def get_last_word_len(sentence: str) -> int:
last_non_whitespace_index = get_last_non_whitespace_index(sentence)
if last_non_whitespace_index == -1:
return 0
i = last_non_whitespace_index
while i >= 0:
if ord(sentence[i]) in UNICODE_WHITESPACE_CHARS:
break
i -= 1
return last_non_whitespace_index - i

def main() -> None:
print(f'{get_last_word_len("Hello how are you") = }')
print(f'{get_last_word_len("Hello how are you ") = }')
print(f'{get_last_word_len("Hello how are you ") = }')
print(f'{get_last_word_len("") = }')
print(f'{get_last_word_len("a ") = }') # Whitespace is a tab character.

if __name__ == '__main__':
main()

Output:

get_last_word_len("Hello how are you") = 3
get_last_word_len("Hello how are you ") = 3
get_last_word_len("Hello how are you ") = 3
get_last_word_len("") = 0
get_last_word_len("a ") = 1


Related Topics



Leave a reply



Submit