Reverse words in a string in C++ without using any built-in function in CPP
In this CPP tutorial, we are going to discuss how to reverse words in a given string without using any built-in function. This question is also being asked in many interviews like Lenskart interview for SDE-II post.
How to input sentence in CPP?
In cpp declaring a string and taking input using cin will ignore the words after the whitespace character.
Like :- Codespeedy is a programming site
Declaring string as string s and input using cin>>s will just store only Codespeedy in string s.
So, to input sentence in CPP one way is to use cin.getline() function.
syntax:- cin.getline(name_of_string , characters_limit);
Declaration:- char s[100];
cin.getline(s,100);
How to check for whitespace in a sentence?
To check for whitespace in a sentence in CPP one way is to use isspace() function.
Syntax:- isspace()
Frequency of each character in a string in c++
Reverse words in a string in C++
Let’s look at the algorithm first to learn how to reverse the words in a string in cpp.
Algorithm
- Input a sentence using cin.getline() function.
- Declare a string array str.
- Now, store each word in a string array by checking that if the character in sentence reach whitespace or not using isspace() function.
- Now, print each word using the index of string array from last to 0 giving whitespace after each word.
CPP code to reverse words in a given string without using any built-in function
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[100];
cin.getline(s,100);
string str[100];
long i,count=-1,c=0;
for (i=0;s[i]!='\0';i++)
{
c++;
}
for (i=0;s[i]!='\0';i++)
{
count++;
if(!isspace(s[i]) && i<c)
{
while(!isspace(s[i]) && i<c)
{
str[count]=str[count]+s[i];
if(isspace(s[i]))
break;
i++;
}
}
}
for (i=4;i>=0;i--)
{
cout<<str[i]<<" ";
}
}INPUT
Codespeedy is a programming site
OUTPUT
site programming a is Codespeedy
Here, str[0]=Codespeedy
str[1]=is
str[2]=a
str[3]=programming
str[4]=site
So, to reverse words in given sentence print the string array from index 4 to 0 using for loop.
cout<<str[4]<<" "<<str[3]<<" "<<str[2]<<" "<<str[1]<<" "<<str[0];
You may learn
Leave a Reply