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

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

问题描述

我正在尝试检查字符串是否是bash中的回文.这是我想出的:

I am trying to check if a string is a palindrome in bash. Here is what I came up with:

#!/bin/bash
read -p "Enter a string: " string
if [[ $string|rev == $string ]]; then
    echo "Palindrome"
fi  

现在,echo $string|rev给出反向字符串.我的逻辑是在if的条件下使用它.效果不是很好.

Now, echo $string|rev gives reversed string. My logic was to use it in the condition for if. That did not work out so well.

那么,如何将rev中的返回值"存储到变量中? 还是直接在有条件的情况下使用它?

So, how can I store the "returned value" from rev into a variable? or use it directly in a condition?

推荐答案

没有echo[[ ... ]]中不必要的引号的另一种变体:

Another variation without echo and unnecessary quoting within [[ ... ]]:

#!/bin/bash
read -p "Enter a string: " string
if [[ $(rev <<< "$string") == "$string" ]]; then
    echo Palindrome
fi

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

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