Strony

środa, 6 lutego 2013

Revert words in a sentence.


Revert words in a sentence, so " The quick brown fox jumped over the lazy dog." becomes "dog. lazy the over jumped fox brown quick The" .

In C:
#include <stdio.h>
void revertWord( char *start, char *end ) {
char temp;
while( start < end ) {
temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
}
void revertString(char *sentence) {
char *start = sentence;
char *end = sentence;
while ( *(++end) ); // to the null
// but don't touch not null
--end;
// all sentence first
revertWord( start, end );
// and now word by word
while ( *start ) { // not null?
// find space if any, move start to it
for (; *start && *start == ' '; ++start );
// find end fo the word, move end to it
for ( end = start; *end && *end != ' '; ++end );
// space or null, back one
--end;
// reverse from start to end
revertWord( start, end );
// next word or null
start = ++end;
}
}
int main() {
char test[] = "The quick brown fox jumped over the lazy dog.";
printf( "before: %s\n", test );
revertString(test);
printf( "after: %s\n", test );
return 0;
}
view raw revert.C hosted with ❤ by GitHub


In C++:
#include <iostream>
#include <sstream>
#include <stack>
using namespace std;
// using stack
string revertStack( string sentence ) {
stringstream inout(sentence);
string word, news;
stack<string> st;
while ( inout >> word ) {
st.push( word );
}
while ( st.size() ) {
news += " " + st.top();
st.pop();
}
return news;
}
int main() {
string sentence = "The quick brown fox jumped over the lazy dog.";
sentence = revertStack( sentence );
cout << sentence << endl;
}
view raw revert.cpp hosted with ❤ by GitHub


In py:
sentence = "The quick brown fox jumped over the lazy dog."
print "before: ", sentence
sentence = " ".join( sentence.split()[::-1] )
print "after: ", sentence


52 > 27 > 4!




Brak komentarzy:

Prześlij komentarz