Length Of Last Word in a String
Last Updated :
23 Jul, 2025
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 : str = "Geeks For Geeks"
Output : 5
length(Geeks)= 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++
// c++ program for the above approach
#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 = "Geeks For Geeks ";
GFG gfg;
cout << "The length of last word is " << gfg.lengthOfLastWord(input) << endl;
return 0;
}
// This code is contributed by prince
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
JavaScript
<script>
// js program for implementation of simple
// approach to find length of last word
function lengthOfLastWord(a)
{
let len = 0;
// String a is 'final'-- can
// not be modified So, create
// a copy and trim the
// spaces from both sides
x = a.trim();
for (let i = 0; i < x.length; i++) {
if (x[i] == ' ') {
len = 0;
}
else {
len++;
}
}
return len;
}
// Driver code
input = "Geeks For Geeks ";
document.write("The length of last word is "+ lengthOfLastWord(input));
</script>
OutputThe 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++
// CPP program for implementation of efficient
// approach to find length of last word
#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--) {
// 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 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
# Driver code
str = "Geeks for Geeks"
print("The length of last word is",
findLength(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
JavaScript
// Function to find length of last word in a string
function length(str) {
let count = 0;
let flag = false;
// Loop through the string backwards
for (let 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
let str = "Geeks for Geeks";
console.log(`The length of last word is ${length(str)}`);
PHP
<?php
// PHP program for implementation of efficient
// approach to find length of last word
function length($str)
{
$count = 0;
$flag = false;
for($i = strlen($str)-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
$str = "Geeks for Geeks";
echo "The length of last word is ", length($str);
// This code is contributed by ajit.
?>
OutputThe 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++
// C++ code for the above aprroach
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int length(string str) {
// Split by space and converting
// String to list and
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();
}
// Driver code
int main() {
string str = "Geeks for Geeks";
cout << "The length of last word is " << length(str) << endl;
return 0;
}
// This code is contributed adityashatmfh
Java
// Java program for implementation of efficient
// approach to find length of last word
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int length(String str) {
// Split by space and converting String to list
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();
}
// Driver code
public static void main(String[] args) {
String str = "Geeks for Geeks";
System.out.println("The length of last word is " + length(str));
}
}
// Contributed by adityasharmadev01
Python3
# Python3 program for implementation of efficient
# approach to find length of last word
def length(str):
# Split by space and converting
# String to list and
lis = list(str.split(" "))
return len(lis[-1])
# Driver code
str = "Geeks for Geeks"
print("The length of last word is",
length(str))
# This code is contributed by vikkycirus
C#
// C# code for the above approach
using System;
public class Program {
static int length(string str)
{
// Split by space and converting
// String to list and
string[] lis = str.Split(' ');
return lis[lis.Length - 1].Length;
} // Driver code
static void Main()
{
string str = "Geeks for Geeks";
Console.WriteLine("The length of last word is "
+ length(str));
}
}
JavaScript
<script>
// Javascript program for implementation
// of efficient approach to find length
// of last word
function length(str)
{
// Split by space and converting
// String to list and
var lis = str.split(" ")
return lis[lis.length - 1].length;
}
// Driver code
var str = "Geeks for Geeks"
document.write("The length of last word is " +
length(str));
// This code is contributed by bunnyram19
</script>
OutputThe length of last word is 5
METHOD 4:Using regular expressions
APPROACH:
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
ALGORITHM:
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) {
// Use regular expressions to find the last word
regex re("[^ ]*$");
smatch match;
regex_search(s, match, re);
string last_word = match.str();
// Return the length of the last word
return last_word.length();
}
int main() {
string s = "Geeks For Geeks";
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) {
// Use regular expressions to find the last word
Pattern pattern = Pattern.compile("[^ ]*$");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String lastWord = matcher.group();
// Return the length of the last word
return lastWord.length();
}
// If no last word is found, return 0
return 0;
}
public static void main(String[] args) {
String s = "Geeks For Geeks";
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):
# use regular expressions to find the last word
last_word = ''.join(re.findall('[^ ]*$', s))
# return the length of the last word
return len(last_word)
s = "Geeks For Geeks"
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
{
// Function to calculate the length of the last word in a string
static int LengthOfLastWord(string s)
{
// Use regular expressions to find the last word
Regex re = new Regex(@"[^ ]*$"); // Define a regular expression to match non-space characters at the end of the string.
Match match = re.Match(s); // Search for the regular expression in the input string.
string lastWord = match.Value; // Get the matched portion as the last word.
// Return the length of the last word
return lastWord.Length; // Return the length of the last word.
}
static void Main()
{
string s = "Geeks For Geeks";
Console.WriteLine(LengthOfLastWord(s)); // Call the function and print the result.
s = "Start Coding Here";
Console.WriteLine(LengthOfLastWord(s)); // Call the function and print the result.
s = "";
Console.WriteLine(LengthOfLastWord(s)); // Call the function and print the result.
}
}
JavaScript
function lengthOfLastWord(s) {
// Use regular expressions to find the last word
const re = /[^ ]*$/;
const match = s.match(re);
if (match) {
const lastWord = match[0];
// Return the length of the last word
return lastWord.length;
} else {
// If no last word is found, return 0
return 0;
}
}
// Main function
const s1 = "Geeks For Geeks";
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem