反转字符串程序

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何编写一个 C 程序来反转给定的字符串。该程序将从用户处获取输入,反转字符串并将结果输出到控制台。这个概念可以用于检查一个字符串是否是回文,因为回文字符串在反转后仍然具有相同的值。

注意:你需要自己创建文件 ~/project/main.c 来练习编码,并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/ControlFlowGroup -.-> c/while_loop("`While Loop`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123323{{"`反转字符串程序`"}} c/for_loop -.-> lab-123323{{"`反转字符串程序`"}} c/while_loop -.-> lab-123323{{"`反转字符串程序`"}} c/strings -.-> lab-123323{{"`反转字符串程序`"}} c/user_input -.-> lab-123323{{"`反转字符串程序`"}} c/output -.-> lab-123323{{"`反转字符串程序`"}} end

声明变量并从用户读取输入

#include <stdio.h>
#include <string.h>

int main() {
   char str[1000], rev[1000];
   int i, j, count = 0;

   printf("Enter a string: ");
   scanf("%s", str);

在这一步中,我们声明了两个字符数组 strrev,以及三个整型变量 ijcountstr 用于存储用户输入的原始字符串,rev 用于存储反转后的字符串。count 用于记录字符串的长度。然后,我们使用 printf 提示用户输入字符串,并使用 scanf 读取输入。

计算字符串的长度

while (str[count] != '\0') {
   count++;
}
j = count - 1;

在这一步中,我们使用 while 循环遍历原始字符串,直到遇到空字符 \0。在每次迭代中,我们递增 count 变量以计算字符串中的字符数。然后,我们将 count - 1 的值赋给 j,因为数组从索引 0 开始,我们希望 j 成为原始字符串中最后一个字符的索引。

反转字符串

for (i = 0; i < count; i++) {
   rev[i] = str[j];
   j--;
}
printf("Reversed string: %s\n", rev);

在这一步中,我们使用 for 循环遍历原始字符串。在每次迭代中,我们将原始字符串中索引 j 处的字符赋值给反转字符串中对应的索引 i。然后,我们递减 j 并重复该过程,直到整个字符串被反转。最后,我们使用 printf 将反转后的字符串输出到控制台。

完整代码

#include <stdio.h>
#include <string.h>

int main() {
   char str[1000], rev[1000];
   int i, j, count = 0;

   printf("Enter a string: ");
   scanf("%s", str);

   while (str[count] != '\0') {
      count++;
   }
   j = count - 1;

   for (i = 0; i < count; i++) {
      rev[i] = str[j];
      j--;
   }
   printf("Reversed string: %s\n", rev);

   return 0;
}

总结

在本实验中,你学习了如何编写一个 C 程序来反转给定的字符串。你学习了如何使用 while 循环计算字符串的长度,以及如何使用 for 循环和索引变量反转字符串。编写程序来操作字符串是 C 编程中的一项重要技能,通过掌握它,你可以完成许多有用的任务。

您可能感兴趣的其他 C 教程