×

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

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.