Microsoft Interview Question
Software Engineer in Tests#include<stdio.h>
void rev(char *r,char *l)
{
char temp;
while(r<l)
{
temp=*r;
*r=*l;
*l=temp;
r++;
l--;
}
}
void revword(char *str)
{
char *end,*x,*y,i;
for(end=str;*end;end++);
//reverse complete sentence
rev(str,end-1);
//reverse word in the sentence
x=y=str;
while(x++<end)
{
if(*x==' '||*x=='\0')
{
rev(y,x-1);
y=x+1;
}
}
}
main()
{
char s[]="my name is anthony";
revword(s);
printf("\nafter rev : %s",s);
return 0;
}
Let me complete your code
void revString(char * str){
int i = 0;
int start = 0, j =0;
char temp;
if (str == null) {
return (char *)0;
} else {
while ( *(str+i) != '\0'){
if (*(str+i) == ' ' || *(str+i) == '\t'){
i++;
} else {
start = i;
j = 0;
while (*(str+i+j) != '\0' || *(str+i+j) != ' ' )
j++;
int k = 0;
while ( k < j - 1 ){
temp = *(str + start + k);
*(str + start + k) = *(str + start + j - 1 - k);
*(str + start + j -1 - k) = temp;
}
i = start + j ;
}
}
}
}
Reverse the whole string first char by char. Then reverse the chars of individual words.
- knap October 15, 2008I wonder if there is a much smarter way of doing the same ! there should be.
Both the steps are orthogonal, so order doesn't matter.