Given a null-terminated string, reverse the words within it (assume that words are separated by one or more spaces). Now do it in-place.
void reverseWords(char *aString)
{
{
Given a null-terminated string, reverse the words within it (assume that words are separated by one or more spaces). Now do it in-place.
1 Comment so far
Leave a comment
This is a version with buffer:
size_t strSize = strlen(aString);
if (strSize == 0) {
return;
}
char *buff = new char[strSize + 1U];
std::memset(buff,0,strSize + 1U);
char *locStr = aString;
char *revPos = NULL;
ptrdiff_t wordSize = 0;
while (*locStr != ”){
char *startPos = locStr;
while((*locStr != ‘ ‘) && (*locStr != ”)) {
locStr++;
}
wordSize = locStr - startPos;
revPos = locStr;
while(wordSize–) {
*buff++ = *(–revPos);
}
while((*locStr == ‘ ‘) && (*locStr != ”)) {
*buff++ = *locStr++;
}
}
delete [] buff;
buff = NULL;
}
This one is in-place:
if (NULL == aString) {
return;
}
char *locStr = aString;
char *revPos = NULL;
double wordSize = 0.0;
int counter = 0;
while (*locStr != ”){
char *startPos = locStr;
char *buff = locStr;
while((*locStr != ‘ ‘) && (*locStr != ”)) {
locStr++;
}
std::modf((locStr - startPos)/2.0,&wordSize);
revPos = locStr;
counter = static_cast(wordSize);
while(counter–) {
char pt = *buff;
*buff++ = *(–revPos);
*revPos = pt;
}
while((*locStr == ‘ ‘) && (*locStr != ”)) {
locStr++;
}
}
}
By kiklop on 12.30.06 10:47 am | Permalink
Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.