本题要求实现一个字符串逆序的简单函数。
void f( char *p );
函数f对p指向的字符串进行逆序操作。要求函数f中不能定义任何数组,不能调用任何字符串处理函数。
#include <stdio.h>
#define MAXS 20
void f( char *p );
void ReadString( char *s ); /* 由裁判实现,略去不表 */
int main()
{
char s[MAXS];
ReadString(s);
f(s);
printf("%s\n", s);
return 0;
}
/* 你的代码将被嵌在这里 */
Hello World!
!dlroW olleH
abcde
edcba
字符串可能包含空格。
解法一:数组
void f( char *p )
{
int cnt = 0;
while(p[cnt] != '\0') {
cnt++;
}
int i;
for(i=0; i<cnt/2; i++) {
char temp = p[i];
p[i] = p[cnt-1-i];
p[cnt-1-i] = temp;
}
}
解法二:指针
void f( char *p )
{
int cnt = 0;
while(*(p+cnt) != '\0') {
cnt++;
}
int i;
for(i=0; i<cnt/2; i++) {
char temp = *(p+i);
*(p+i) = *(p+cnt-1-i);
*(p+cnt-1-i) = temp;
}
}