Created
July 31, 2017 08:28
-
-
Save 0001vrn/7c3b3f1815548cef50bf44c03d641f55 to your computer and use it in GitHub Desktop.
Reverse words in a given string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Given a String of length N reverse the words in it. Words are separated by dots. | |
| By : Varun Thakur | |
| Date : 31/07/2017 | |
| */ | |
| #include <bits/stdc++.h> | |
| using namespace std; | |
| void reverse(char *begin, char *end) | |
| { | |
| char temp; | |
| while (begin < end) | |
| { | |
| temp = *begin; | |
| *begin++ = *end; | |
| *end-- = temp; | |
| } | |
| } | |
| void reverseWords(string& str) | |
| { | |
| int len = str.length(); | |
| char *s = new char[len+1]; | |
| copy(str.begin(),str.end(),s); | |
| s[len]='\0'; | |
| char *word_begin = s; | |
| char *temp = s; | |
| while(*temp) | |
| { | |
| temp++; | |
| if(*temp == '\0') | |
| { | |
| reverse(word_begin,temp-1); | |
| } | |
| else if(*temp == '.') | |
| { | |
| reverse(word_begin, temp-1); | |
| word_begin = temp+1; | |
| } | |
| } | |
| reverse(s,temp-1); | |
| str.assign(s,len); | |
| } | |
| int main() { | |
| //code | |
| int t;cin>>t; | |
| while(t--){ | |
| string s;cin>>s; | |
| reverseWords(s); | |
| cout<<s<<'\n'; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment