Thu May 25 11:41:00 UTC 2023 inscode

上级 e5529530
#include <stdio.h> // 包含标准输入输出库的头文件
#define LEN 5 // 定义宏常量LEN为5
#include <stdio.h>
#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
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册