Title: Enter an English sentence, flipping the order of the words in the sentence, but the order of the characters within the word is unchanged. Words are separated by spaces in sentences. For simplicity, punctuation is treated like ordinary letters.
For example, enter "I am a student.", then output "student." A am I ".
Analysis: Because writing string-related code can reflect the programmer's programming ability and programming habits, string-related problems have been the programmer's written test, interview questions Hot topic. Many companies, including Microsoft, have been favored by many of them.
Because the subject needs to flip the sentence, we first reverse all the characters in the sentence. In this case, not only the order of the words in the sentence is flipped, but also the characters in the word are flipped. We invert the characters within each word. Because the characters within the word are flipped two times, the order remains the same as the order in which they were entered.
Or take the above input as an example. Flip "I am a student." All the characters in the ". Tneduts a Ma I", and then flip the order of the characters in each word to get "students." A AM I "is the output that meets the requirements.
Reference code:
voidReverse (Char*pbegin,Char*pEnd) { if(Pbegin = = NULL | | pEnd = =NULL)return; while(Pbegin <pEnd) { Chartemp = *Pbegin; *pbegin = *pEnd; *pend =temp; Pbegin+ +, PEnd--; }}/////////////////////////////////////////////////////////////////////////Reverse the word order in a sentence, but maintain the character//order inside a word//input:pdata-the sentence to be reversed///////////////////////////////////////////////////////////////////////Char* Reversesentence (Char*pData) { if(PData = =NULL)returnNULL; Char*pbegin =PData; Char*pend =PData; while(*pend! =' /') PEnd++; PEnd--; //Reverse the whole sentenceReverse (Pbegin, pEnd); //Reverse every word in the sentencePbegin = PEnd =PData; while(*pbegin! =' /') { if(*pbegin = =' ') {Pbegin++; PEnd++; Continue; } //A Word is between with pbegin and pEnd, reverse it Else if(*pend = =' '|| *pend = =' /') {Reverse (Pbegin,--pEnd); Pbegin= ++pEnd; } Else{pEnd++; } } returnPData;}
Original: reprint please specify source http://zhedahht.blog.163.com/
Programmer Interview 50 Questions (3)-Flips the order of words in a sentence [algorithm]