检查字符串是否为回文

C++C++Beginner
立即练习

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

介绍

在本实验中,你将学习如何编写 C++ 代码来检查给定的字符串是否是回文(Palindrome)。回文是一种单词、短语或字符序列,无论正向还是反向读取,其内容都相同。例如,"level" 是一个回文,因为无论正向还是反向读取,它都是一样的。在本实验中,我们将编写一个简单的程序,该程序将接收一个字符串作为输入,并检查它是否是回文。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/strings -.-> lab-96180{{"`检查字符串是否为回文`"}} cpp/conditions -.-> lab-96180{{"`检查字符串是否为回文`"}} cpp/for_loop -.-> lab-96180{{"`检查字符串是否为回文`"}} cpp/output -.-> lab-96180{{"`检查字符串是否为回文`"}} cpp/user_input -.-> lab-96180{{"`检查字符串是否为回文`"}} cpp/files -.-> lab-96180{{"`检查字符串是否为回文`"}} cpp/code_formatting -.-> lab-96180{{"`检查字符串是否为回文`"}} end

创建新项目和文件

使用以下命令将当前目录切换到项目目录:

cd project

接下来,我们将使用 touchVim 等编辑器在项目文件夹中创建一个新的 C++ 文件。在本实验中,我们将使用以下命令创建一个名为 main.cpp 的文件:

touch main.cpp

编写 C++ 代码检查回文

  • 在我们的 C++ 程序中,可以使用 string 库从用户那里获取输入字符串并执行回文检查。以下是一个简单的程序来实现这一功能:
#include <bits/stdc++.h>
using namespace std;
int main() {
    string str, output;
    cout << "Enter a string: ";
    cin >> str;
    int n = str.length();
    for (int i = 0; i < n / 2; i++) {
        if (str[i] != str[n - i - 1]) {
            output = "Given string is not a Palindrome";
            break;
        }
        else {
            output = "Given string is a Palindrome";
        }
    }
    cout << output << endl;
return 0;
}

编译和运行代码

  • 在终端中使用 g++ 编译器编译代码,命令如下:
g++ main.cpp -o main
  • 成功编译代码后,可以使用以下命令运行程序:
./main
  • 程序会提示你输入一个字符串。你可以输入任意字符串,程序将显示该字符串是否是回文。

最终代码

以下是完整的 C++ 代码,用于检查给定字符串是否是回文:

#include <bits/stdc++.h>
using namespace std;
int main() {
    string str, output;
    cout << "Enter a string: ";
    cin >> str;
    int n = str.length();
    for (int i = 0; i < n / 2; i++) {
        if (str[i] != str[n - i - 1]) {
            output = "Given string is not a Palindrome";
            break;
        }
        else {
            output = "Given string is a Palindrome";
        }
    }
    cout << output << endl;
return 0;
}

总结

在本实验中,你学习了如何用 C++ 创建一个简单的程序来检查给定字符串是否是回文。你学会了如何使用 C++ 的字符串库从用户那里获取输入并执行回文检查。我们希望你现在对 C++ 编程语言有了更好的理解,并能够将这些知识应用到未来创建更复杂的程序中。

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