# Length Of Last Word in a String

Given a string s consisting of upper/lower-case alphabets and empty space characters ‘ ‘, return length of the last word in the string. If the last word does not exist, return 0.

Examples:

```Input  : str = "Geeks For Geeks"
Output : 5
length(Geeks)= 5

Input : str = "Start Coding Here"
Output : 4
length(Here) = 4

Input  :  **
Output : 0
```

## Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Approach 1: Iterate String from index 0
If we iterate the string from left to right, we would have to be careful about the spaces after the last word. The spaces before the first word can be ignored easily. However, it is difficult to detect the length of the last word if there are spaces at the end of the String. This can be handled by trimming the spaces before or at the end of the string. If modifying the given String is restricted, we need to create a copy of the string and trim spaces from that.

## C++

 `// C++ program for implementation of simple ` `// approach to find length of last word ` `#include ` `#include ` `using` `namespace` `std; ` ` `  `int` `lengthOfLastWord(string a) ` `{ ` `    ``int` `len = 0; ` `     `  `    ``/* String a is 'final'-- can not be modified ` `    ``So, create a copy and trim the spaces from ` `    ``both sides */` `    ``string str(a); ` `    ``boost::trim_right(str); ` `    ``for` `(``int` `i = 0; i < str.length(); i++)  ` `    ``{ ` `        ``if` `(str.at(i) == ``' '``) ` `            ``len = 0; ` `        ``else` `            ``len++; ` `    ``} ` `    ``return` `len; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``string input = ``"Geeks For Geeks "``; ` `    ``cout << ``"The length of last word is "`  `        ``<< lengthOfLastWord(input); ` `} ` ` `  `// This code is contributed by Rajput-Ji `

## Java

 `// Java program for implementation of simple ` `// approach to find length of last word ` `public` `class` `GFG { ` `    ``public` `int` `lengthOfLastWord(``final` `String a) ` `    ``{ ` `        ``int` `len = ``0``; ` ` `  `        ``/* String a is 'final'-- can not be modified ` `           ``So, create a copy and trim the spaces from ` `           ``both sides */` `        ``String x = a.trim(); ` ` `  `        ``for` `(``int` `i = ``0``; i < x.length(); i++) { ` `            ``if` `(x.charAt(i) == ``' '``) ` `                ``len = ``0``; ` `            ``else` `                ``len++; ` `        ``} ` ` `  `        ``return` `len; ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` `        ``String input = ``"Geeks For Geeks  "``; ` `        ``GFG gfg = ``new` `GFG(); ` `        ``System.out.println(``"The length of last word is "` `+ gfg.lengthOfLastWord(input)); ` `    ``} ` `} `

## Python3

 `# Python3 program for implementation of simple ` `# approach to find length of last word ` `def` `lengthOfLastWord(a): ` `    ``l ``=` `0` ` `  `    ``# String a is 'final'-- can not be modified ` `    ``# So, create a copy and trim the spaces from ` `    ``# both sides ` `    ``x ``=` `a.strip() ` ` `  `    ``for` `i ``in` `range``(``len``(x)): ` `        ``if` `x[i] ``=``=` `" "``: ` `            ``l ``=` `0` `        ``else``: ` `            ``l ``+``=` `1` `    ``return` `l ` ` `  `# Driver code ` `if` `__name__ ``=``=` `"__main__"``: ` `    ``inp ``=` `"Geeks For Geeks "` `    ``print``(``"The length of last word is"``,  ` `                 ``lengthOfLastWord(inp)) ` ` `  `# This code is contributed by ` `# sanjeev2552 `

## C#

 `// C# program for implementation of simple ` `// approach to find length of last word ` `using` `System; ` ` `  `class` `GFG { ` ` `  `    ``public` `virtual` `int` `lengthOfLastWord(``string` `a) ` `    ``{ ` `        ``int` `len = 0; ` ` `  `        ``// String a is 'final'-- can ` `        ``// not be modified So, create ` `        ``// a copy and trim the ` `        ``// spaces from both sides ` `        ``string` `x = a.Trim(); ` ` `  `        ``for` `(``int` `i = 0; i < x.Length; i++) { ` `            ``if` `(x[i] == ``' '``) { ` `                ``len = 0; ` `            ``} ` `            ``else` `{ ` `                ``len++; ` `            ``} ` `        ``} ` ` `  `        ``return` `len; ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `Main(``string``[] args) ` `    ``{ ` `        ``string` `input = ``"Geeks For Geeks "``; ` `        ``GFG gfg = ``new` `GFG(); ` `        ``Console.WriteLine(``"The length of last word is "` `                          ``+ gfg.lengthOfLastWord(input)); ` `    ``} ` `} ` ` `  `// This code is contributed by shrikanth13 `

Output:

```Length of the last word is 5
```

Approach 2: Iterate string from the last index. This idea is more efficient since we can easily ignore the spaces from the last. The idea is to start incrementing the count when you encounter the first alphabet from the last and stop when you encounter a space after those alphabets.

## C++

 `// CPP program for implementation of efficient ` `// approach to find length of last word ` `#include ` `#include ` `using` `namespace` `std; ` ` `  `int` `length(string str) ` `{ ` `    ``int` `count = 0; ` `    ``bool` `flag = ``false``; ` `    ``for` `(``int` `i = str.length() - 1; i >= 0; i--) { ` `        ``// Once the first character from last ` `        ``// is encountered, set char_flag to true. ` `        ``if` `((str[i] >= ``'a'` `&& str[i] <= ``'z'``) || (str[i] >= ``'A'` `&& str[i] <= ``'Z'``)) { ` `            ``flag = ``true``; ` `            ``count++; ` `        ``} ` `        ``// When the first space after the ` `        ``// characters (from the last) is ` `        ``// encountered, return the length ` `        ``// of the last word ` `        ``else` `{ ` `            ``if` `(flag == ``true``) ` `                ``return` `count; ` `        ``} ` `    ``} ` `    ``return` `count; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``string str = ``"Geeks for Geeks"``; ` `    ``cout << ``"The length of last word is "` `<< length(str); ` `    ``return` `0; ` `} ` ` `  `// This code is contributed by rahulkumawat2107 `

## Java

 `// Java program for implementation of efficient ` `// approach to find length of last word ` `public` `class` `GFG { ` `    ``public` `int` `lengthOfLastWord(``final` `String a) ` `    ``{ ` `        ``boolean` `char_flag = ``false``; ` `        ``int` `len = ``0``; ` `        ``for` `(``int` `i = a.length() - ``1``; i >= ``0``; i--) { ` `            ``if` `(Character.isLetter(a.charAt(i))) { ` `                ``// Once the first character from last ` `                ``// is encountered, set char_flag to true. ` `                ``char_flag = ``true``; ` `                ``len++; ` `            ``} ` `            ``else` `{ ` `                ``// When the first space after the characters ` `                ``// (from the last) is encountered, return the ` `                ``// length of the last word ` `                ``if` `(char_flag == ``true``) ` `                    ``return` `len; ` `            ``} ` `        ``} ` `        ``return` `len; ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` `        ``String input = ``"Geeks For Geeks  "``; ` `        ``GFG gfg = ``new` `GFG(); ` `        ``System.out.println(``"The length of last word is "` `+ gfg.lengthOfLastWord(input)); ` `    ``} ` `} `

## Python3

 `# Python3 program for implementation of efficient ` `# approach to find length of last word ` `def` `length(``str``): ` ` `  `    ``count ``=` `0``; ` `    ``flag ``=` `False``; ` `    ``length ``=` `len``(``str``)``-``1``; ` `    ``while``(length !``=` `0``): ` `        ``if``(``str``[length] ``=``=` `' '``): ` `            ``return` `count; ` `        ``else``: ` `            ``count ``+``=` `1``; ` `        ``length ``-``=` `1``; ` `    ``return` `count; ` ` `  `# Driver code ` `str` `=` `"Geeks for Geeks"``; ` `print``(``"The length of last word is"``,  ` `                      ``length(``str``)); ` ` `  `# This code is contributed by Rajput Ji `

## C#

 `// C# program for implementation of efficient ` `// approach to find length of last word ` `using` `System; ` ` `  `class` `GFG { ` ` `  `    ``public` `virtual` `int` `lengthOfLastWord(``string` `a) ` `    ``{ ` `        ``bool` `char_flag = ``false``; ` `        ``int` `len = 0; ` `        ``for` `(``int` `i = a.Length - 1; i >= 0; i--) { ` `            ``if` `(``char``.IsLetter(a[i])) { ` `                ``// Once the first character from last ` `                ``// is encountered, set char_flag to true. ` `                ``char_flag = ``true``; ` `                ``len++; ` `            ``} ` `            ``else` `{ ` `                ``// When the first space after the ` `                ``// characters (from the last) is ` `                ``// encountered, return the length ` `                ``// of the last word ` `                ``if` `(char_flag == ``true``) { ` `                    ``return` `len; ` `                ``} ` `            ``} ` `        ``} ` `        ``return` `len; ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `Main(``string``[] args) ` `    ``{ ` `        ``string` `input = ``"Geeks For Geeks "``; ` `        ``GFG gfg = ``new` `GFG(); ` `        ``Console.WriteLine(``"The length of last word is "` `+ gfg.lengthOfLastWord(input)); ` `    ``} ` `} ` ` `  `// This code is contributed by Shrikant13 `

## PHP

 `=0 ; ``\$i``--) ` `    ``{ ` `        ``// Once the first character from last  ` `        ``// is encountered, set char_flag to true. ` `        ``if``( (``\$str``[``\$i``] >=``'a'` `&& ``\$str``[``\$i``]<=``'z'``) ||  ` `            ``(``\$str``[``\$i``] >=``'A'` `&& ``\$str``[``\$i``]<=``'Z'``)) ` `        ``{ ` `            ``\$flag` `= true; ` `            ``\$count``++; ` `        ``} ` `         `  `        ``// When the first space after the  ` `        ``// characters (from the last) is  ` `        ``// encountered, return the length  ` `        ``// of the last word  ` `        ``else` `        ``{ ` `            ``if``(``\$flag` `== true) ` `                ``return` `\$count``; ` `        ``} ` `         `  `    ``} ` `    ``return` `\$count``; ` `} ` ` `  `// Driver code ` `\$str` `= ``"Geeks for Geeks"``; ` `echo` `"The length of last word is "``, length(``\$str``); ` ` `  `// This code is contributed by ajit. ` `?> `

Output:

```Length of the last word is 5
```

This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
{"ft_lang_label":"__label__en","ft_lang_prob":0.6722896,"math_prob":0.9205454,"size":9060,"snap":"2020-34-2020-40","text_gpt3_token_len":2572,"char_repetition_ratio":0.15967314,"word_repetition_ratio":0.37966102,"special_character_ratio":0.30728477,"punctuation_ratio":0.11573237,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9965272,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-08-06T09:44:24Z\",\"WARC-Record-ID\":\"<urn:uuid:6154819e-33d3-42a2-9bc6-5b1a2fe432e2>\",\"Content-Length\":\"177494\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:96d400ef-84a5-4d9d-9e05-3c8a5658636c>\",\"WARC-Concurrent-To\":\"<urn:uuid:886839e0-8d6e-43cd-9602-7dac34e23802>\",\"WARC-IP-Address\":\"23.217.129.72\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/length-of-last-word-in-a-string/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:ASUHBGQDJIFDAQJY4TOH6ENGCNQKBFYM\",\"WARC-Block-Digest\":\"sha1:3FRHPTBNFIMKZBA5K5LCRCMSDM64AWXV\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-34/CC-MAIN-2020-34_segments_1596439736902.24_warc_CC-MAIN-20200806091418-20200806121418-00183.warc.gz\"}"}