C++ - 检查结构数据类型中的单词是否为回文

C++ - Checking if a word is palindrome in struct data type

我想知道如何检查一个词在结构数据类型或对象中是否是回文,无论你想怎么称呼它。我想从文件中读取数据然后我需要检查我读过的那种类型的单词是否是回文。我还需要颠倒单词的顺序,但我做到了,所以不需要任何帮助。

代码如下:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

struct lettersStr
{
    string name;
    string object;

};
int main(int argc, char** argv) 
{
    ifstream letter;
    letter.open("letter.txt");
    lettersStr things[200];
    int numberOfThings= 0;
    while(letter >> letter[numberOfThings].name >> letter[numberOfThings].object)
    {
        numberOfThings++;
    }

    for (int i = 0; i < numberOfThings; i++)
    {
        cout << letter[i].name << " " << letter[i].object<< endl;
    }
    string names;
    for (int i = 0; i < numberOfThings; i++)
    {
        names= things[i].name;
    }

    for (int i = numberOfThings- 1; i >= 0; i--)
    {
        cout << things[i].name << endl;
    }
    bool x = true;
    int j = names.length() - 1;
    for (int i = 0; i < j; i++,j--)
    {
        if (things[i].name.at(i) != things[i].name.at(j))
        x = false;

        if (x)
        {
            cout << "String is a palindrome ";
        }
        else
        cout << "String is not a palindrome";
    }

这里是 cout:

Kayak Audi
Ahmed Golf7
Ahmed
Kayak
String is not a palindrome
String is not a palindrome

我认为主要问题是:

for (int i = 0; i < j; i++,j--)
    {
        if (things[i].name.at(i) != things[i].name.at(j))
        x = false;

如您所见,它无法找到检查单词是否为回文的正确方法。 P.S: 如果这是一个愚蠢的问题,我很抱歉,我是 C++ 编程的初学者。 干杯

正如评论中已经指出的那样,for (int i = 0; i < j; i++,j--) 循环遍历 things 和它们的 name 的字母同时。您还必须考虑比较小写字母和大写字母的情况,例如 'Kayak' 开头和结尾的 'K' 和 'k'。您可以为此使用 std::tolower

这是一个例子 (live demo):

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

bool is_palindrome(std::string name)
{
    if (name.empty())
        return false;


    // As has been pointed out, you can also use std::equal.
    // However, this is closer to your original approach.
    for (unsigned int i = 0, j = name.length()-1; i < j; i++,j--)
    {
        if (std::tolower(name.at(i)) != std::tolower(name.at(j)))
            return false;
    }
    return true;
}

struct lettersStr
{
    string name;
    string object;
};

int main(int argc, char** argv) 
{

    std::vector<lettersStr> vec = {lettersStr{"Kayak","Boat"},lettersStr{"Audi","Car"}};

    for (const auto &obj : vec)
        if (is_palindrome(obj.name))
            std::cout << obj.name << " is a palindrome" << std::endl;
        else
            std::cout << obj.name << " isn't a palindrome" << std::endl;
}

它给出了输出:

Kayak is a palindrome
Audi isn't a palindrome