×

Reverse String Word-Wise in C++

What is a reversed String?

Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is that in reverse a string, we reverse every alphabet and in the reverse a word we reverse every word in a sentence. For example, take the sentence "I love to code" then the reverse  string word will be code to love I.

Program

Example-1: Using Standard Template Library

Now lets us see how to write a c++ code for this using the standard templet library:

// This c++ program is written to reverse words of a string.
//As we are using string and input and output operations, we are using the bits/stdc++.h header files
// This header file will import all the files which are needed.
#include <bits/stdc++.h>
using namespace std;


// We are creating a function to reverse a string.
string reverseString(string str)
{


	// First, we need to reverse a string using the built-in reverse keyword.
	reverse(str.begin(), str.end());


	//We need to add space to the End of the reversed string so that the last word will also be reversed
	str.insert(str.end(), ' ');
//integer n will have a length of the string
	int n = str.length();


	int j = 0;


	// We need to find the space and then reverse the string
	//We are using the for loop to iterate through every letter;
	for (int i = 0; i < n; i++) {


		// If space is encountered
		if (str[i] == ' ') {
			reverse(str.begin() + j,
					str.begin() + i);


			// Update the starting index
			// for the next word to reverse
			j = i + 1;
		}
	}


	// Remove spaces from the End of the
	// word that we appended
	str.pop_back();


	// Return the reversed string
	return str;
}


// Creating the main function
int main()
{
	string str = "I love to code";


	// calling the function
	string rev = reverseString(str);


	// Print the reversed string
	cout << rev;
	return 0;
}
//End of the code to reverse a string using the standard template library. 

Output:

Reverse string word-wise in C++

Explanation:

The above code demonstrates how to reverse string words using the standard template library. In the code, we have used the function to reverse the words. In the function, we used the reverse keyword to reverse the string. In the main function, we gave a string and passed it to the function by calling it. Then we added a space to the End of the reversed string so that we could even reverse the last word. Then we created a for loop to iterate through every letter of the string. During the iteration, if we find any space, we need to reverse that part of the word. To reverse the word, we have used the reverse keyword. Then we returned the word.

Example-2 Without Using Standard Template Library

Now let's see code how we can write the program without using the standard templet library:

// This c++ program is written to reverse words of a string.
//As we are using string and input and output operations, we are using the bits/stdc++.h header files
// This header file will import all the files which are needed.




#include <bits/stdc++.h>
using namespace std;


//function used to reverse a string


void reversed(string& s, int l, int r)
{


	while (l < r) {


		// Swap characters at l and r
		swap(s[l], s[r]);
		l++;
		r--;
	}
}


//function to reverse the given string
string reverseString(string str)
{


	// Add space at the End so that the
	// last word is also reversed
	str.insert(str.end(), ' ');


	int n = str.length();


	int j = 0;


	// Find spaces and reverse all words
	// before that
	for (int i = 0; i < n; i++) {


		// If space is encountered
		if (str[i] == ' ') {


			//function call to our custom
			// reverse function()
			reversed(str, j, i - 1);


			// Update the starting index
			// for the next word to reverse
			j = i + 1;
		}
	}


	// Remove spaces from the End of the
	// word that we appended
	str.pop_back();


	// Reverse the whole string
	reversed(str, 0, str.length() - 1);


	// Return the reversed string
	return str;
}


// Driver code
int main()
{
	string str = "I love to code";


	// Function call
	string rev = reverseString(str);


	// Print the reversed string
	cout << rev;
	return 0;
}

Output:

Reverse string word-wise in C++

Explanation:

The above code is written to demonstrate how to reverse a string word. In the above code, we have created a function to swap the letters. We have also created another function that will loop through each letter. If we find any space, the swap function in the another function will be called by the End of the for loop, and the words will be reversed.


Related Topics

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.