检查字符串是否为回文

C++C++Beginner
立即练习

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

介绍

在本实验中,你将学习如何编写一个 C++ 程序来检查给定的字符串是否是回文。回文是指与其反转字符串相同的字符串。为了检查回文,我们将反转给定的字符串并将其与原始字符串进行比较。如果两个字符串相同,则给定的字符串是回文,否则不是。


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/StandardLibraryGroup(["`Standard Library`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/arrays("`Arrays`") 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/StandardLibraryGroup -.-> cpp/string_manipulation("`String Manipulation`") cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/arrays -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/strings -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/conditions -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/for_loop -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/output -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/user_input -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/string_manipulation -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/comments -.-> lab-96181{{"`检查字符串是否为回文`"}} cpp/code_formatting -.-> lab-96181{{"`检查字符串是否为回文`"}} end

包含所需的库并定义 main() 函数

首先,我们将包含所需的库并定义 main() 函数。

#include <iostream>
#include <string.h>

using namespace std;

int main() {
  // code goes here
  return 0;
}

从用户获取输入字符串

接下来,我们将从用户获取输入字符串并将其存储在一个字符数组中。

char inputStr[100];
cout << "Enter a string: ";
cin >> inputStr;

获取输入字符串的长度

我们将使用 strlen() 函数计算输入字符串的长度。

int strLength = strlen(inputStr);

创建用于存储反转字符串的数组

接下来,我们将创建一个用于存储反转字符串的数组。

char reverseStr[strLength];

反转输入字符串

现在,我们将反转输入字符串并将其存储在新创建的用于存储反转字符串的数组中。

for(int i = 0; i < strLength; i++) {
    reverseStr[i] = inputStr[strLength - 1 - i];
}

比较原始字符串和反转字符串

最后,我们将比较原始字符串和反转字符串,以检查输入字符串是否是回文。

if(strcmp(inputStr, reverseStr) == 0) {
    cout << inputStr << " is a palindrome." << endl;
} else {
    cout << inputStr << " is not a palindrome." << endl;
}

完整代码

#include <iostream>
#include <string.h>

using namespace std;

int main() {
    char inputStr[100];
    cout << "Enter a string: ";
    cin >> inputStr;

    int strLength = strlen(inputStr);
    char reverseStr[strLength];

    for(int i = 0; i < strLength; i++) {
        reverseStr[i] = inputStr[strLength - 1 - i];
    }

    if(strcmp(inputStr, reverseStr) == 0) {
        cout << inputStr << " is a palindrome." << endl;
    } else {
        cout << inputStr << " is not a palindrome." << endl;
    }

    return 0;
}

总结

在本实验中,你学习了如何编写一个 C++ 程序来检查给定的字符串是否是回文。现在,你可以使用这个程序快速检查任何字符串是否是回文。

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