Sentence flip
I am Superman ---> Superman am I
This question is relatively simple:
Ideas:
(1) split the original string into words, and then combine the words into reverse strings;
The function is as follows:
# Include "stdafx. H"
# Include "stdlib. H"
# Include <string>
# Include <list>
Using namespace STD;
Bool inversestring (const STD: String strsrc, STD: string & strdsc)
{
List <string> substring;
List <string >:: iterator ITER;
Int ibegin = 0, iend = 0;
// If it is null
If (strsrc. Empty ())
{
Return false;
}
// Extract each sub-word string
For (unsigned int I = 0; I <strsrc. Size (); I ++)
{
// It is a space.
If (strsrc [I] = 0x20)
{
Iend = I;
}
// It is a legal substring
If (iend-ibegin)> 0)
{
STD: String tmpstr = strsrc. substr (ibegin, iend-ibegin );
Substring. push_front (tmpstr );
Ibegin = I;
}
}
// Last word string
STD: String tmpstr = strsrc. substr (ibegin );
Substring. push_front (tmpstr );
For (iter = substring. Begin (); iter! = Substring. End (); ITER ++)
{
Strdsc. append (* ITER );
// Add Spaces
Strdsc. append ("");
}
Return true;
}
Int main (void)
{
String strsrc = "I am Superman ";
STD: String strdesc = "";
Inversestring (strsrc, strdesc );
Printf ("DESC string is: % s \ n", strdesc. c_str ());
}
The above is my solution. If you have better algorithms, please let me know! I wrote this function without considering the fact that the original string contains multiple spaces!