gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:32:28 25 4
gpt4 key购买 nike

我想知道如何检查一个单词是否是结构数据类型或对象中的回文。我想从文件中读取数据,然后需要检查所读取的单词类型是否为回文。我也需要颠倒单词的顺序,但是我做到了,所以不需要任何帮助。

这是代码:

#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";
}

这是提示:
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;

如您所见,它不会提供正确的方法来检查单词是否为回文。
附注:如果这是一个愚蠢的问题,对不起,我是C++编程的初学者。
干杯

最佳答案

正如评论中已经指出的那样,for (int i = 0; i < j; i++,j--)同时循环通过things及其name的字母。您还必须考虑在“皮划艇”的开头和结尾处比较大小写字母(例如“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

关于c++ - C++-检查单词是否为结构数据类型的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61751542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com