From 22c87b1740c7fbbbefc5a09daa5660f57fe2f522 Mon Sep 17 00:00:00 2001 From: 64428d3e4c6fa56f8d8a0e92 <64428d3e4c6fa56f8d8a0e92@devide> Date: Thu, 25 May 2023 11:41:00 +0000 Subject: [PATCH] Thu May 25 11:41:00 UTC 2023 inscode --- target/C.c | 66 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 50 insertions(+), 16 deletions(-) diff --git a/target/C.c b/target/C.c index 57aa033..a5b7ab6 100644 --- a/target/C.c +++ b/target/C.c @@ -1,22 +1,56 @@ -#include // 包含标准输入输出库的头文件 -#define LEN 5 // 定义宏常量LEN为5 +#include +#define STR_LEN 101 -int main(int argc, char** argv) // 主函数 +void reverse(char *str) { - char *fruits[LEN] = { // 定义字符串数组fruits,包含5个字符串元素 - "apple", // 第一个元素为"apple" - "cherry", // 第二个元素为"cherry" - "grape", // 第三个元素为"grape" - "peach", // 第四个元素为"peach" - "watermelon" // 第五个元素为"watermelon" - }; - - for (int i = 0; i < LEN; i++) // 外层循环,控制访问fruits中的元素 + char* head = str; + char* tail = str; + char ch; + + while(*tail++); + tail -= 2; + + while(head < tail) { - for (int j = 0; fruits[i][j] != '\0'; j++) // 内层循环,控制访问fruits[i]中的字符 - printf("%c", *(*(fruits + i) + j)); // 输出字符 - printf("\n"); // 每输出一个字符串就换行 + ch = *head; + *head++ = *tail; + *tail-- = ch; } +} + - return 0; // 返回0表示程序正常结束 + +void reverse(char *str) //定义函数reverse,参数为指向字符的指针 +{ + char* head = str; //定义指针head指向str的首地址 + char* tail = str; //定义指针tail指向str的首地址 + char ch; //定义字符变量ch用于交换字符 + + while(*tail ) //循环找到字符串的尾部,判断tail指向的字符是否为'\0' + { + tail++; //指针向后移动直到指向'\0' + } + tail -= 2; //将tail的指针移动到倒数第二个字符 + + while(head < tail) //交换头尾指针指向的字符 + { + ch = *head; //将head指向的字符赋值给ch + *head = *tail;//将tail指向的字符赋值给head所指向的字符 + *tail-- = ch; //将ch赋值给tail指向的字符,tail向前移动一位 + head++; //head向后移动一位 + } } + + + +int main(int argc, char** argv) +{ + char str[STR_LEN]; + char *rev_str = NULL; + printf("请输入一个字符串(length<=100):\n"); + scanf("%s", str); + reverse(str); + printf("反转后的字符串为:\n%s", str); + + return 0; +} \ No newline at end of file -- GitLab