I had this interview question like a year ago and was asked to code, on a piece of paper, how to reverse each word of a string. Since I am used to Java, I proposed the obvious answer of using split + reverse, which are native commands in Java. I was then told I couldn't use those, so I floundered and ended up with a really terrible solution (even though it technically would've worked).
Anyway, it was bugging me lately, so I gave it a shot in straight C, which I am not very good at, so it took me a good while to actually get it working.
I was wondering:
- Is this a good solution?
- Have I forgotten anything obvious?
- Have I done anything non-kosher in the C world?
Again, I'm not very good at C, so even small points will probably help me out.
#include <stdio.h>
void reverseString(char* start, char* end){
while (start < end){
char temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
}
char* word_start_index(char* p)
{
while((*p != '\0') && (*p == ' ')){
++p;
}
if(*p == '\0')
return NULL;
else
return p;
}
char* word_end_index(char* p)
{
while((*p != '\0') && (*p != ' ')){
++p;
}
return p-1;
}
void main(){
char arr[] = "kevin is a good programmer";
char* test = arr;
while (test != '\0'){
char* curWordStart = word_start_index(test);
if (curWordStart == NULL)
break;
char* curWordEnd = word_end_index(curWordStart);
reverseString(curWordStart, curWordEnd);
test = curWordEnd + 1;
}
printf("%s \n", arr);
}
Also, would taking a different approach, like in higher level languages of breaking the string into an array of strings (so I guess a 2D array of chars), then stepping through and reversing each one, be a good approach as well? I thought about this first and was unable to hash it out.