2.1 Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
C的字符串有段时间没用过了,出了几个问题。1. 在计算右边界时,需要记录s的位置,不能*s++;同时right要自减,否则right指向了'\0'。2. 一开始数组定义成了char *str,但是运行时出错,提示写内存出错,才反应过来这样定义的是字符串常量,改成char str[]就可以了。
#include "stdio.h"
void Reverse(char * s)
{
int left = 0, right = 0;
char * sTemp = s;
// calculate the right pointer
while (*sTemp++ != NULL)
right++;
right--;
// swap two chars
while (left < right)
{
char tmp = s[left];
s[left++] = s[right];
s[right--] = tmp;
}
}
void main(void)
{
char str[] = "faeofo;jih";
Reverse(str);
printf("%s", str);
}