
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Length of Last Word in C++
Suppose we have a string s. s can hold any English letters and white-spaces. We have to find the length of last word in the string. If there is no last word, then return 0.
So, if the input is like "I love Programming", then the output will be 11
To solve this, we will follow these steps −
n := 0
for each word temp in a string −
n := size of temp
return n
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int lengthOfLastWord(string s){ stringstream str(s); string temp; int n = 0; while (str >> temp) n = temp.size(); return n; } }; main(){ Solution ob; cout << (ob.lengthOfLastWord("I love Programming")); }
Input
"I love Programming"
Output
11
- Related Articles
- Python - Find the length of the last word in a string
- Finding the length of second last word in a sentence in JavaScript
- PHP program to find the length of the last word in the string
- Word Ladder (Length of shortest chain to reach a target word) in C++
- Finding average word length of sentences - JavaScript
- Find First and Last Word of a File Containing String in Java
- Capitalize last letter and Lowercase first letter of a word in Java
- C++ program for length of the longest word in a sentence
- Program to find length of longest diminishing word chain in Python?
- MySQL query to extract last word from a field?
- Program to find length longest prefix sequence of a word array in Python
- Function to find the length of the second smallest word in a string in JavaScript
- Find the first maximum length even word from a string in C++
- Python Program to return the Length of the Longest Word from the List of Words
- Program to find length of longest word that can be formed from given letters in python

Advertisements