InterviewSolution
| 1. |
Given a string as an input, write a program to reverse the words in the given string and display the new string. |
|
Answer» Example: We maintain a vector of strings. We traverse the given string and keep forming the word until a space is encountered. When space is encountered we ADD the word formed to the vector of strings. In the end, we print the vector of strings in reverse format. Code : #include <bits/stdc++.h>USING namespace std;// function to reverse the words in an inputted stringvoid displayModifiedString(string str){ // vector to store all the words of the inputted string vector<string> arr; string temp = ""; // VARIABLE to form each word of the string for (int i = 0; i < str.length(); i++) { // if space is encountered, we push the formed word to the vector if (str[i] == ' ') { arr.push_back(temp); temp = "";// RESETTING the temp variable } // we keep forming the word else temp += str[i]; } arr.push_back(temp);// we push back the last formed word // we print the vector in the reverse order for (int i = arr.size() - 1; i > 0; i--) cout << arr[i] << " "; cout << arr[0] << endl;} int main(){ string str = "InterviewBit is best"; displayModifiedString(str); return 0;}Output : best is InterviewBitExplanation : In the above code, the function displayModifiedString takes a string input and displays the modified string with words in reverse order. We keep forming a word until a space character is found. Once space is found, we push back the word to the vector. Lastly, we display the vector in reverse order. |
|