This site features a collection of common technical interview questions gathered by a group of programmers who have been through, and given, lots of technical interviews. There is an emphasis on C++ and game programming technical interviews, but most of the questions are relevant to any technical interview.
string this Reverse

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)
{

1 Comment so far
Leave a comment

This is a version with buffer:

void reverseWords(char *aString) {
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:

void reverseWords(char *&aString) {
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++;
}
}
}


Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.


Do you have a technical interview question you would like to submit? Some tips you would like to pass on? Just want to say hi? Feel free to contact us