void reverse_str01(char* str){
int i,len,mid,temp;
len = strlen(str);
mid = len%2==0 ? len/2 : len/2+1;
for(i=0;i<mid;i++){
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
void reverse_str02(char* str){
int len,start,end;
len = strlen(str);
start = 0;
end = len - 1;
while(start<end){
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
// 利用指针方式
void reverse_str03(char* str){
int len = strlen(str);
char *start = str; // 指向第一个字符的指针
char *end = str + len - 1; // 指向最后一个字符的指针
while(start<end){
char temp = *start;
*start++ = *end;
*end-- = temp;
}
}
void reverse_str04(char* str){
char *p1, *p2;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2){
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
}
int main(){
char str[] = "abcdefg";
// reverse_str01(str);
// reverse_str02(str);
// reverse_str03(str);
reverse_str04(str);
printf("%s\n",str);
return 0;
}
|