![]() |
VOOZH | about |
Given a string s consisting of upper/lower-case alphabets and empty space characters ' ', return the length of the last word in the string. If the last word does not exist, return 0.
Examples:
Input : s = "Geeks For Geeks"
Output : 5
Explanation: length(Geeks)= 5Input : s = "Start Coding Here"
Output : 4
Explanation: length(Here) = 4Input : s= " "
Output : 0
Table of Content
The idea is to split the given string into separate words using spaces as delimiters. All extracted words are stored in a array, and the length of the last stored word is returned as the answer.
The length of last word is 5
The idea is to use a regular expression to directly extract the last word from the string. The regex pattern searches for the sequence of non-space characters occurring at the end of the string. Once the last word is found, its length is returned.
The length of last word is 5
The idea is to first remove leading and trailing spaces from the string. Then, traverse the string character by character while counting the length of the current word. Whenever a space is encountered, the counter is reset. At the end of traversal, the counter stores the length of the last word.
The length of last word is 5