编写程序来检查字符串是否是回文。 [英] Write a program to check a string is palindrome or not.

查看:372
本文介绍了编写程序来检查字符串是否是回文。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;

int main( )
{
    char str[80];

    cin.getline(str, 80);
	
    int l;     
    for(l = 0; str[l] != '\0'; l++);

    int i;
    for(i = 0; (i < l/2) && (str[i] == str[l - i - 1]); i++);

    if(i == l/2)
        cout << "Palindrome";
    else
        cout << "Not a palindrome";
	
    return 0;
}





例如,如果单词是 gig 那么它是回文,但如果这个词是 Gig 然后它不起作用。



任何人都可以编辑代码,以便它可以接受大写和小写字母。



For Example if the word is "gig" then it is palindrome but if the word is "Gig" then it is not working.

Can anyone edit the code so that It can accept both capital and small letter.

推荐答案

这样做的常用方法是使用 tolower()功能。



因此,通过它运行输入,并使用您的算法,您就完成了。
A common way of doing this, is using the tolower() function.

So run the input trough it, and use your algorithm and you are done.


当您使用较低级别的语言时,我建议使用较低级别的技术;它应该给你的老师留下深刻的印象。

在ASCII编码中,大写字母与小写字母之间的区别是一位。



例如:



As you are using a lower-level language, I suggest using a lower-level technique; it should impress your teacher very much.
In the ASCII encoding, the difference between uppercase letters and their lowercase counterparts, is one bit.

For example:

A == 65 == 1000001
a == 97 == 1100001
__________________
XOR  32    0100000





我相信你可以很容易地实现一个函数来测试两个字符,如果它们是字母,那么执行一个忽略那一位的逐位比较。





您的整体实施仍然需要忽略标点符号等。



去挂萨拉米香肠,我是烤宽面条猪!


请看我对这个问题的评论。



是的,Gig不是回文,在某种意义上你定义了它。这是因为'g'!='G'。如果您想要不区分大小写的回文测试,请使用不区分大小写的检查。在比较两个字符之前,将两者都转换为小写或大写。请参阅:

tolower - C ++参考 [ ^ ],

toupper - C ++参考 [ ^ ]。



-SA
Please see my comment to the question.

And yes, "Gig" is not a palindrome, in the sense you defined it. This is because 'g' != 'G'. If you want a case-insensitive palindrome test, use case-insensitive check-up. Before comparing two characters, convert both to lower case or to upper case. Please see:
tolower - C++ Reference[^],
toupper - C++ Reference[^].

—SA


这篇关于编写程序来检查字符串是否是回文。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆