Reverse String according to the number of words


String manipulation is an essential skill in programming, as it helps us process and analyze text data efficiently. C++ provides a rich set of string manipulation functions and objects, making it easier to work with text data.

In this article, we will discuss how to reverse a string according to the number of words in C++.

Approaches

Approach 1 − Using stringstreams and vectors

Approach 2 − Using substrings and string manipulation functions

Syntax

String object in C++: The std::string class is a part of the C++ Standard Library and provides various string manipulation functions.

String manipulation functions: Some common string manipulation functions in C++ include length(), substr(), find(), erase(), and replace().

std::string reverseStringByWords(const std::string& input) {}
std::reverse(words.begin(), words.end());

Approach 1:- Using stringstreams and vectors

This approach employed in the code involves converting the input string into a sequence of words using a stringstream object. The words are then extracted one by one from the stream and stored in a collection of strings represented by a vector.

Subsequently, the collection of words is reversed using the reverse function from the algorithm library. The reversed words are then joined together to form the final output string, with a space appended after each word except the last one.

Algorithm

  • Start

  • Take the input string.

  • Create a stringstream from the input string.

  • Initialize an empty vector to store words.

  • Iterate through the stringstream to extract words.

  • Extract a word from the stringstream.

  • Push the extracted word into the vector.

  • Reverse the vector containing the words.

  • Initialize an empty output string.

  • Iterate through the reversed vector to form the output string.

  • Add each word from the reversed vector to the output string, followed by a space.

  • Remove the last space from the output string.

  • Return the output string.

  • End

Example

The code embodies a procedure that inverts the sequence of words in a specified string. This is accomplished by first transforming the input string into a word-based stream through utilization of a stringstream object. Subsequently, the words are extracted one at a time and placed into a vector. Then, the reverse function from the algorithm library is employed to reverse the vector. Finally, the inverted words are joined together to form the conclusive output string, with spaces inserted after each word, excluding the final one. The last space is then deleted from the output string, rendering a compact and comprehensible solution that makes the most of Standard Library features like stringstreams, vectors, and the algorithm library.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

std::string reverseStringByWords(const std::string& input) {
   std::stringstream ss(input);
   std::string word;
   std::vector<std::string> words;

   while (ss >> word) {
      words.push_back(word);
   }

   std::reverse(words.begin(), words.end());

   std::string output;
   for (const auto& w : words) {
      output += w + " ";
   }

   output.pop_back(); // Remove the last space
   return output;
}

int main() {
   std::string input = "Hello, how are you?";
   std::string output = reverseStringByWords(input);
   std::cout << "Input: " << input << std :: endl;
   std:: cout << "Output: " << output << std :: endl;
   return 0;
}

Output

Input: Hello, how are you?
Output: you? are how Hello,

Approach 2:- Using substrings and string manipulation functions

Approach 2 is an alternative solution for reversing the order of words in a string. It uses substrings and string manipulation functions, rather than stringstreams and vectors as in Approach 1.

This approach involves manually dividing the input string into substrings, which represent individual words. The substrings are concatenated in reverse order to form the final output string.

Algorithm

  • Start

  • Take the input string.

  • Initialize two size_t variables, start and end, to hold the start and end positions of words in the input string.

  • Initialize the start position to 0.

  • Find the position of the first space in the input string and store it in the end variable.

  • Initialize an empty output string.

  • Iterate through the input string and extract words using substrings.

  • Extract the substring from the start position to the end position.

  • Concatenate the extracted substring in front of the output string, followed by a space.

  • Update the start position to the position after the end position.

  • Find the next space in the input string starting from the new start position and update the end position.

  • After the loop, extract the last word from the input string using the

  • End

Example

The code is a solution for reversing the order of words in a given string. It does this by dividing the input string into substrings using the find function and concatenating these substrings in reverse order to form the output string. The last space character is then removed from the output string using the pop_back function. This approach is more manual and low-level compared to Approach 1 and requires a deeper understanding of string manipulation. The code takes a given input string, divides it into substrings, reverses the order of these substrings, and returns the final output string.

#include <iostream>
#include <string>

std::string reverseStringByWords(const std::string& input) {
   size_t start = 0;
   size_t end = input.find(' ');
   std::string output;

   while (end != std::string::npos) {
      output = input.substr(start, end - start) + " " + output;
      start = end + 1;
      end = input.find(' ', start);
   }
    
   output = input.substr(start) + " " + output;
   output.pop_back(); // Remove the last space
   return output;
}

int main() {
   std::string input = "Hello, how are you?";
   std::string output = reverseStringByWords(input);
   std::cout << "Input: " << input << std::endl;
   std::cout << "Output: " << output << std::endl;

   return 0;
}

Output

Input: Hello, how are you?
Output: you? are how Hello,

Conclusion

Importance of string manipulation in programming: Mastering string manipulation techniques is crucial for any programmer, as text data is ubiquitous in software development. Understanding various approaches to string manipulation can help developers write more efficient, maintainable, and robust code.

Updated on: 21-Jul-2023

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements