P216 例5.写一个函数,使输入的一个字符串按反序存放,在主函数中输入和输出字符串
方法一:通过数组逆序的方法:
#define _CRT_SECURE_NO_WARNINGS#include#includeint main() {void reverse(char string[]);char str[50] = {0};//定义字符串数组时要确定数组长度,如果不确定,可能会发生越界访问printf("请输入一个字符串:");/*scanf("%s", str);*/gets(str);reverse(str);printf("\n反序存放后:");printf("%s\n",str);return 0;}void reverse(char string[]) {int len = strlen(string);int left = 0;int right = len - 1;char tmp;while (left < right) {tmp = string[left];string[left] = string[right];string[right] = tmp;left++;right--;}}
运行结果:
方法二:运用指针
#define _CRT_SECURE_NO_WARNINGS#include#includeint main() {/*void reverse(char string[]);*/void reverse(char *stirng);char str[50] = {0};//定义字符串数组时要确定数组长度,如果不确定,可能会发生越界访问printf("请输入一个字符串:");/*scanf("%s", str);*/gets(str);reverse(str);printf("\n反序存放后:");printf("%s\n",str);return 0;}void reverse(char* string) {int len = strlen(string);char tmp;char* left = string;char* right = string + len - 1;while (left < right) {tmp = *left;*left = *right;*right = tmp;left++;right--;}}
运行结果:
方法三:指针+递归方法
#includeint my_strlen(char * p) {int count = 0;while (*p != '\0') {count++;p++;}return count;}void reverse_string(char*str) {int len = my_strlen(str);char temp = *(str);*str = *(str + len - 1);*(str + len - 1) = '\0';if( my_strlen(str+1) >= 2) {reverse_string(str + 1);}*(str + len - 1) = temp;}int main() {char arr[30] = {"0"};gets(arr);reverse_string(arr);printf("%s\n", arr);return 0;}
运行结果: