检查字符串是否是回文 [英] Check if a string is palindrome

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

问题描述


可能重复:

查找给定的字符串是否是回文或不是回文

我需要创建一个允许用户输入字符串的程序,我的程序将检查他们输入的字符串是否是回文(可以是

I need to create a program that allows a user to input a string and my program will check to see if that string they entered is a palindrome (word that can be read the same backwards as it can forwards).

推荐答案

只需将字符串与自身颠倒即可:

Just compare the string with itself reversed:

string input;

cout << "Please enter a string: ";
cin >> input;

if (input == string(input.rbegin(), input.rend())) {
    cout << input << " is a palindrome";
}

string 接受开始和结束迭代器,并从这两个迭代器之间的字符创建字符串。因为 rbegin()是字符串的结尾,并且递增它通过字符串向后,我们创建的字符串将具有 input <

This constructor of string takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin() is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input added to it in reverse, reversing the string.

然后你只需将它与输入进行比较即可。

Then you just compare it to input and if they are equal, it is a palindrome.

这不包括大小写或空格,所以你必须自己改进。

This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.

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

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