
- 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
Program to reverse a sentence words stored as character array in C++
Suppose we have one input string sentence where each element is stored as single character, we have to reverse the strings word by word.
So, if the input is like ["t","h","e"," ","m","a","n"," ","i","s"," ","n","l","c","e"], then the output will be ["n","l","c","e"," ","i","s"," ","m","a","n"," ","t","h","e"]
To solve this, we will follow these steps −
reverse the array s
j := 0
n := size of s
for initialize i := 0, when i < n, update (increase i by 1), do −
if s[i] is same as ' ', then −
reverse the array s from index j to i
j := i + 1
reverse the array s from index j to n
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: void reverseWords(vector<char>& s) { reverse(s.begin(), s.end()); int j = 0; int n = s.size(); for(int i = 0; i < n; i++){ if(s[i] == ' '){ reverse(s.begin() + j, s.begin() + i); j = i + 1; } } reverse(s.begin() + j, s.begin() + n); } }; main(){ Solution ob; vector<char> v = {'t','h','e',' ','m','a','n',' ','i','s',' ','n','i','c','e'}; ob.reverseWords(v); print_vector(v); }
Input
{'t','h','e',' ','m','a','n',' ','i','s',' ','n','i','c','e'}
Output
[n, i, c, e, , i, s, , m, a, n, , t, h, e, ]
- Related Articles
- Reverse all the words of sentence JavaScript
- Python program to count words in a sentence
- Java program to reverse each word in a sentence
- Python program to reverse each word in a sentence?
- C++ program to Reverse a Sentence Using Recursion
- Java Program to Reverse a Sentence Using Recursion
- Golang Program to Reverse a Sentence using Recursion
- Python program to sort Palindrome Words in a Sentence
- Count words in a sentence in Python program
- C# program to Reverse words in a string
- Java Program to convert first character uppercase in a sentence
- C Program to convert first character uppercase in a sentence
- C# Program to convert first character uppercase in a sentence
- C# Program to replace a character with asterisks in a sentence
- Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Advertisements