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.
Input : str = "Beginner For Beginner"
Output : 5
length(Beginner)= 5
Input : str = "Start Coding Here"
Output : 4
length(Here) = 4
Input : **
Output : 0
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++
#include <iostream>
#include <string>
using namespace std;
class GFG {
public :
int lengthOfLastWord( const string& a) {
int len = 0;
string x = a;
x.erase(0, x.find_first_not_of( " " ));
x.erase(x.find_last_not_of( " " ) + 1);
for ( int i = 0; i < x.length(); i++) {
if (x[i] == ' ' )
len = 0;
else
len++;
}
return len;
}
};
int main() {
string input = "Beginner For Beginner " ;
GFG gfg;
cout << "The length of last word is " << gfg.lengthOfLastWord(input) << endl;
return 0;
}
|
Java
public class GFG {
public int lengthOfLastWord( final String a)
{
int len = 0 ;
String x = a.trim();
for ( int i = 0 ; i < x.length(); i++) {
if (x.charAt(i) == ' ' )
len = 0 ;
else
len++;
}
return len;
}
public static void main(String[] args)
{
String input = "Beginner For Beginner " ;
GFG gfg = new GFG();
System.out.println( "The length of last word is "
+ gfg.lengthOfLastWord(input));
}
}
|
Python3
def lengthOfLastWord(a):
l = 0
x = a.strip()
for i in range ( len (x)):
if x[i] = = " " :
l = 0
else :
l + = 1
return l
if __name__ = = "__main__" :
inp = "Beginner For Beginner "
print ( "The length of last word is" ,
lengthOfLastWord(inp))
|
C#
using System;
class GFG {
public virtual int lengthOfLastWord( string a)
{
int len = 0;
string x = a.Trim();
for ( int i = 0; i < x.Length; i++) {
if (x[i] == ' ' ) {
len = 0;
}
else {
len++;
}
}
return len;
}
public static void Main( string [] args)
{
string input = "Beginner For Beginner " ;
GFG gfg = new GFG();
Console.WriteLine( "The length of last word is "
+ gfg.lengthOfLastWord(input));
}
}
|
Javascript
<script>
function lengthOfLastWord(a)
{
let len = 0;
x = a.trim();
for (let i = 0; i < x.length; i++) {
if (x[i] == ' ' ) {
len = 0;
}
else {
len++;
}
}
return len;
}
input = "Beginner For Beginner " ;
document.write( "The length of last word is " + lengthOfLastWord(input));
</script>
|
Output
The length of last word is 5
Approach 2: Iterate the 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++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int length(string str)
{
int count = 0;
bool flag = false ;
for ( int i = str.length() - 1; i >= 0; i--) {
if ((str[i] >= 'a' && str[i] <= 'z' )
|| (str[i] >= 'A' && str[i] <= 'Z' )) {
flag = true ;
count++;
}
else {
if (flag == true )
return count;
}
}
return count;
}
int main()
{
string str = "Beginner for Beginner" ;
cout << "The length of last word is " << length(str);
return 0;
}
|
Java
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))) {
char_flag = true ;
len++;
}
else {
if (char_flag == true )
return len;
}
}
return len;
}
public static void main(String[] args)
{
String input = "Beginner For Beginner " ;
GFG gfg = new GFG();
System.out.println( "The length of last word is "
+ gfg.lengthOfLastWord(input));
}
}
|
Python3
def findLength( str ):
count = 0
flag = False
for i in range ( len ( str ) - 1 , - 1 , - 1 ):
if (( str [i] > = 'a' and str [i] < = 'z' ) or ( str [i] > = 'A' and str [i] < = 'Z' )):
flag = True
count + = 1
elif (flag = = True ):
return count
return count
str = "Beginner for Beginner"
print ( "The length of last word is" ,
findLength( str ))
|
C#
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])) {
char_flag = true ;
len++;
}
else {
if (char_flag == true ) {
return len;
}
}
}
return len;
}
public static void Main( string [] args)
{
string input = "Beginner For Beginner " ;
GFG gfg = new GFG();
Console.WriteLine( "The length of last word is "
+ gfg.lengthOfLastWord(input));
}
}
|
Javascript
function length(str) {
let count = 0;
let flag = false ;
for (let i = str.length - 1; i >= 0; i--) {
if ((str[i] >= 'a' && str[i] <= 'z' )
|| (str[i] >= 'A' && str[i] <= 'Z' )) {
flag = true ;
count++;
}
else {
if (flag == true )
return count;
}
}
return count;
}
let str = "Beginner for Beginner" ;
console.log(`The length of last word is ${length(str)}`);
|
PHP
<?php
function length( $str )
{
$count = 0;
$flag = false;
for ( $i = strlen ( $str )-1 ; $i >=0 ; $i --)
{
if ( ( $str [ $i ] >= 'a' && $str [ $i ]<= 'z' ) ||
( $str [ $i ] >= 'A' && $str [ $i ]<= 'Z' ))
{
$flag = true;
$count ++;
}
else
{
if ( $flag == true)
return $count ;
}
}
return $count ;
}
$str = "Beginner for Beginner" ;
echo "The length of last word is " , length( $str );
?>
|
Output
The length of last word is 5
Method #3 : Using split() and list
- As all the words in a sentence are separated by spaces.
- We have to split the sentence by spaces using split().
- We split all the words by spaces and store them in a list.
- Print the length of the last word of the list.
Below is the implementation:
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int length(string str) {
vector<string> lis;
string word = "" ;
for ( char c : str) {
if (c == ' ' ) {
lis.push_back(word);
word = "" ;
} else {
word += c;
}
}
lis.push_back(word);
return lis.back().length();
}
int main() {
string str = "Beginner for Beginner" ;
cout << "The length of last word is " << length(str) << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int length(String str) {
List<String> lis = new ArrayList<>();
String word = "" ;
for ( char c : str.toCharArray()) {
if (c == ' ' ) {
lis.add(word);
word = "" ;
} else {
word += c;
}
}
lis.add(word);
return lis.get(lis.size() - 1 ).length();
}
public static void main(String[] args) {
String str = "Beginner for Beginner" ;
System.out.println( "The length of last word is " + length(str));
}
}
|
Python3
def length( str ):
lis = list ( str .split( " " ))
return len (lis[ - 1 ])
str = "Beginner for Beginner"
print ( "The length of last word is" ,
length( str ))
|
C#
using System;
public class Program {
static int length( string str)
{
string [] lis = str.Split( ' ' );
return lis[lis.Length - 1].Length;
}
static void Main()
{
string str = "Beginner for Beginner" ;
Console.WriteLine( "The length of last word is "
+ length(str));
}
}
|
Javascript
<script>
function length(str)
{
var lis = str.split( " " )
return lis[lis.length - 1].length;
}
var str = "Beginner for Beginner"
document.write( "The length of last word is " +
length(str));
</script>
|
Output
The length of last word is 5
METHOD 4:Using regular expressions
The regular expression essentially matches all non-space characters at the end of the string. The re.findall() function then returns a list of all non-overlapping matches in the input string, which in this case is just a single match consisting of the last word. Finally, the join() function is used to join the list of characters into a single string, and the length of this string (i.e., the length of the last word) is returned by the functio
1.Import the re module for regular expressions
2.Use the findall() function to find all non-space characters at the end of the string
3.Join the resulting list of characters into a string
4.Return the length of the resulting string
C++
#include <iostream>
#include <regex>
using namespace std;
int length_of_last_word_4(string s) {
regex re( "[^ ]*$" );
smatch match;
regex_search(s, match, re);
string last_word = match.str();
return last_word.length();
}
int main() {
string s = "Beginner For Beginner" ;
cout << length_of_last_word_4(s) << endl;
s = "Start Coding Here" ;
cout << length_of_last_word_4(s) << endl;
s = "" ;
cout << length_of_last_word_4(s) << endl;
return 0;
}
|
Java
import java.util.regex.*;
public class Main {
public static int lengthOfLastWord(String s) {
Pattern pattern = Pattern.compile( "[^ ]*$" );
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String lastWord = matcher.group();
return lastWord.length();
}
return 0 ;
}
public static void main(String[] args) {
String s = "Beginner For Beginner" ;
System.out.println(lengthOfLastWord(s));
s = "Start Coding Here" ;
System.out.println(lengthOfLastWord(s));
s = "" ;
System.out.println(lengthOfLastWord(s));
}
}
|
Python3
import re
def length_of_last_word_4(s):
last_word = ' '.join(re.findall(' [^ ] * $', s))
return len (last_word)
s = "Beginner For Beginner"
print (length_of_last_word_4(s))
s = "Start Coding Here"
print (length_of_last_word_4(s))
s = ""
print (length_of_last_word_4(s))
|
C#
using System;
using System.Text.RegularExpressions;
class Program
{
static int LengthOfLastWord( string s)
{
Regex re = new Regex( @"[^ ]*$" );
Match match = re.Match(s);
string lastWord = match.Value;
return lastWord.Length;
}
static void Main()
{
string s = "Beginner For Beginner" ;
Console.WriteLine(LengthOfLastWord(s));
s = "Start Coding Here" ;
Console.WriteLine(LengthOfLastWord(s));
s = "" ;
Console.WriteLine(LengthOfLastWord(s));
}
}
|
Javascript
function lengthOfLastWord(s) {
const re = /[^ ]*$/;
const match = s.match(re);
if (match) {
const lastWord = match[0];
return lastWord.length;
} else {
return 0;
}
}
const s1 = "Beginner For Beginner" ;
console.log( "Length of the last word in '" + s1 + "': " + lengthOfLastWord(s1));
const s2 = "Start Coding Here" ;
console.log( "Length of the last word in '" + s2 + "': " + lengthOfLastWord(s2));
const s3 = "" ;
console.log( "Length of the last word in an empty string: " + lengthOfLastWord(s3));
|
Time complexity: O(n), where n is the length of the input string
Space complexity: O(n), where n is the length of the input string
This article is contributed by Saloni Baweja.