1、变量实现
#include<iostream>
#include<assert.h>
char* Myoverturn(char* str, int n){
assert(str);
char tmp;
char* left = str;
char* right = str + strlen(str) - 1;
//while(left<right){ //全部翻转
while (n--){
tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
return left;
}
int main(){
char arr[] = "abcdefg";
Myoverturn(arr, 2);
printf("翻转后字符串:%s\n", arr);
system("pause");
return 0;
}
结果:
2、不使用变量
#include<iostream>
#include<assert.h>
char* Myoverturn(char* str, int n){
assert(str);
int len = strlen(str)-1;
//for (int i = 0; i < len - i; i++){ //,去掉传入参数n,就可以全部翻转
for (int i = 0; i < n;i++){
str[i] = str[i] ^ str[len - i];
str[len - i] = str[i] ^ str[len - i];
str[i] = str[i] ^ str[len - i];
}
return str;
}
int main(){
char arr[] = "abcdefg";
Myoverturn(arr,1);
printf("翻转后字符串:%s\n", arr);
system("pause");
return 0;
}
结果: