Microsoft Interview Question
Software Engineer in Tests<pre lang="c" line="1" title="CodeMonkey21804" class="run-this">#include<stdio.h>
#include<string.h>
/* code for in place reverse with given start and end pointer of a char buf */
void reverse(char * p, char * q){
int j;
int len = (int)(q-p)+1;
for(char *i = p, j = 0; j< len/2; i++){
char t = *i;
* i = *(q-j);
*(q-j) = t;
j++;
}
}
int main(){
char a[50]= "Arjun is a student of CS Ph.D. at UIC.";
reverse(a, a+strlen(a)-1);
/* crude way of dealing with the boundary case */
a[strlen(a)]=' ';
a[strlen(a)+1]=0;
printf("\n %s ", a);
char *p=a, *q;
for(int i=0; i<strlen(a); i++){
if(a[i]==' '){
q=a+i-1;
reverse(p, q);
p=a+i+1;
}
}
printf("\n %s \n", a);
return 0;
}</pre><pre title="CodeMonkey21804" input="yes">
</pre>
void reverse(char *k)
{
while(*k)
{
int a = reverseword(k);
k += a;
if(*k)
k++;
}
}
int reverseword(char *s)
{
int start = 0,length = 0;
char *p = s;
while(*p != ' ' && *p != ',' && *p != '\0')
{
length++;
p++;
}
for(int i=start,j = length-1;i<j;i++,j--)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
}
return (length - start);
}
code is simple and can be self understood...
first reverse the each word and then reverse the whole string simple
code :
void Reverse(char *str)
{
int n;
char temp;
char f,s;
n=strlen(str);
for(i=0;i<=n-1;)
{
for(j=i+1;str[j]!=' ';j++);
i=j+1;
j--;
for(f=i,s=j;f<j;f++,s--)
{
temp=str[f];
str[f]=str[s];
str[s]=temp;
}
}
for(i=0,j=n-1;i<j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
Reverse each word...
- S October 09, 2010Reverse full string...