实现一句英文的逆序输出----微软面试题
如: 输入 i love china; 输出 china love i
方法一:
#include <stdio.h>
#define N 32
int get_data(char *dest, int num);
int reverse_word(char *str);
int main()
{
char buff[N];
get_data(buff,N);
puts(buff);
reverse_word(buff);
puts(buff);
return 0;
}
void swap(char *head, char *tail)
{
while(head < tail)
{
*head ^= *tail;
*tail ^= *head;
*head ++ ^= *tail --;
}
}
int reverse_word(char *str)
{
char *head = str,
*tail = str;
while('\0' != *tail)
tail ++;
swap(head, tail - 1);
while('\0' != *head)
{
while(32 == *head)
head ++;
tail = head;
while(32 != *tail && '\0' != *tail)
tail ++;
swap(head, tail - 1 );
head = tail;
}
return 0;
}
int get_data(char *dest, int num)
{
char ch;
int count = 0;
if(NULL == dest || num < 1)
return 0;
while('\n' != (ch = getchar()) && count < num - 1)
{
if(ch >= 'a' && ch <= 'z')
;
else if(ch >= 'A' && ch <= 'Z')
ch += 32;
else
ch = 32;
dest[count ++] = ch;
}
dest[count] = '\0';
return count;
}
方法二:
#include<stdio.h>
#define N 30
#if 0
void swap(char *src,char *dest);
int get_data(char *dest,int num);
int reverse_word(char *str);
int main()
{
char str[N];
get_data(str,15);
puts(str);
reverse_word(str);
puts(str);
return 0;
}
int reverse_word(char *str)
{
char *head = str,
*tail = str;
while(*tail != '\0')
tail ++;
swap(head,tail-1);
while(*head != '\0')
{
while(*head == 32)
head++;
tail = head;
while(*tail != '\0'&& *tail != 32)
tail++;
swap(head,tail-1);
head = tail;
}
return 0;
}
void swap(char *src, char *dest)
{
while(src<dest)
{
*src^=*dest;
*dest^=*src;
*src++^=*dest--;
}
}
#endif
int get_data(char *dest,int num)
{
char ch;
int count = 0;
if(dest == NULL || num < 1)
return 0;
while('\n' != (ch = getchar())&&count<num-1 )
{
if(ch >= 'a'&&ch <= 'z')
;
else if(ch >= 'A'&&ch <= 'Z')
{
ch+=32;
}
else
{
ch = 32;
}
dest[count++] = ch;
}
dest[count] = '\0' ;
return count;
}
#if 0
int main()
{
int len,count=0;
char str[N];
char *pe,
*pf=str,
*p=str;
len=get_data(str,15);
pe = str + len - 1;
for(p=str+len-1;p>=str;p--)
{
if(*p == ' ')
{
pf = p+1;
while(pe >= pf)
{
printf("%c",*pf++);
}
pe = p-1;
count++;
}
// while(count--)
putchar(' ');
}
p = str;
while(pe >= p)
{
printf("%c",*p++);
}
return 0;
}
#endif
int main()
{
char buff[N][N];
char string[N];
get_data(string,15);
puts(string);
int i=0,j=0,k=0,len=0;
while(string[i] != '\0')
{
if(string[i] == ' ')
{
buff[j][k] = string[i];
buff[j][k+1] = '\0';
j++;
len++;
k=0;
}
else
{
buff[j][k] = string[i];
k++;
}
i++;
}
for(j=len;j>=0;j--)
{
printf("%s",buff[j]);
printf("%c",' ');
}
return 0;
}
从解题思路和可读性上将个人更偏向方法二