Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Reverse words in a given string solution in c++

#include<iostream>
#include<stack>
using namespace std;

string reverseWords(string S)
{
	stack<char> s;
	string ans;
	for (int i = S.length()-1; i >= 0; i--)
	{
		if (s.empty())
		{
			s.push(S[i]);
		}
		else if (!(s.empty()))
		{
			if (s.top() == '.')
			{
				s.pop();
				while (!(s.empty()))
				{
					ans += s.top();
					s.pop();
				}
				ans += '.';
			}
			
			s.push(S[i]);
	
		}
	}
	while (s.size())
	{
		ans += s.top();
		s.pop();
	}
	return ans;
}
int main()
{
	string s;
	cout << "Enter string: ";
	cin >> s;

	string result;
	result = reverseWords(s);
	cout << "result: " << result << "
";

	return 0;
}
Source by www.codegrepper.com #
 
PREVIOUS NEXT
Tagged: #Reverse #words #string #solution
ADD COMMENT
Topic
Name
4+4 =