From f1bedf05e88053dc83b8cd28f9b0dbc2dd5091e8 Mon Sep 17 00:00:00 2001 From: Rohan Singh Rathore Date: Sat, 16 Oct 2021 11:08:03 +0530 Subject: [PATCH] Create reverse_string.cpp --- reverse_string.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 reverse_string.cpp diff --git a/reverse_string.cpp b/reverse_string.cpp new file mode 100644 index 0000000..bf07242 --- /dev/null +++ b/reverse_string.cpp @@ -0,0 +1,53 @@ +/* +Input: s = “getting good at coding needs a lot of practice” +Output: s = “practice of lot a needs coding at good getting” +*/ + + +// C++ program to reverse a string +#include +using namespace std; + +// Function to reverse words*/ +void reverseWords(string s) +{ + + // temporary vector to store all words + vector tmp; + string str = ""; + for (int i = 0; i < s.length(); i++) + { + + // Check if we encounter space + // push word(str) to vector + // and make str NULL + if (s[i] == ' ') + { + tmp.push_back(str); + str = ""; + } + + // Else add character to + // str to form current word + else + str += s[i]; + } + + // Last word remaining,add it to vector + tmp.push_back(str); + + // Now print from last to first in vector + int i; + for (i = tmp.size() - 1; i > 0; i--) + cout << tmp[i] << " "; + // Last word remaining,print it + cout << tmp[0] << endl; +} + +// Driver Code +int main() +{ + string s = "i like this program very much"; + reverseWords(s); + return 0; +}