I had this interview question like a year ago, I 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, then when told I couldn't use those I floundered and ended up with a really terrible solution (even though it technically would've worked).
Anyway lately it was bugging me 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, and I was wondering, is this a good solution? Did I forget anything obvious or do anything non-kosher in the C world? Again I'm not very good at C so even small little points will probably help me out.
The code:
#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 2-d array of chars), then stepping through and reversing each one would be good approach as well? I thought about this first and was unable to hash it out.