Skip to content

Create reverse_string.cpp #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions reverse_string.cpp
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
using namespace std;

// Function to reverse words*/
void reverseWords(string s)
{

// temporary vector to store all words
vector<string> 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;
}