bash 检查字符串是否为回文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26743049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:42:22  来源:igfitidea点击:

checking if a string is a palindrome

linuxbashscripting

提问by Little Child

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

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

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

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

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

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

那么,如何将“返回值”存储rev到变量中?还是直接在条件下使用?

回答by glenn Hymanman

A bash-only implementation:

仅 bash 的实现:

is_palindrome () { 
    local word=
    local len=$((${#word} - 1))
    local i
    for ((i=0; i <= (len/2); i++)); do
        [[ ${word:i:1} == ${word:len-i:1} ]] || return 1
    done
    return 0
}

for word in hello kayak; do
    if is_palindrome $word; then
        echo $word is a palindrome
    else
        echo $word is NOT a palindrome
    fi
done

Inspired by gniourf_gniourf:

受 gniourf_gniourf 的启发:

is_palindrome() {
  (( ${#1} <= 1 )) && return 0
  [[ ${1:0:1} != ${1: -1} ]] && return 1
  is_palindrome ${1:1: 1}
}

I bet the performance of this truly recursive call really sucks.

我敢打赌这个真正递归调用的性能真的很糟糕。

回答by janos

Another variation without echoand unnecessary quoting within [[ ... ]]:

另一种没有echo和不必要的引用的变体[[ ... ]]

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

回答by that other guy

Use $(command substitution):

使用$(command substitution)

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

回答by Alex

Maybe it is not the best implementation, but if you need something with sh only

也许这不是最好的实现,但如果你只需要 sh 的东西

#!/bin/sh

#get character <str> <num_of_char>. Please, remember that indexing is from 1
get_character() {
  echo "" | cut -c ""
}

for i in $(seq $((${#1} / 2))); do
  if [ "$(get_character "" "$i")" != "$(get_character "" $((${#1} - i + 1)))" ]; then
    echo "NO"
    exit 0
  fi
done

echo "YES"

and canonical way with bash as well

以及 bash 的规范方式

for i in $(seq 0 $((${#1} / 2 - 1))); do
  if [ "${1:$i:1}" != "${1:$((${#1} - i - 1)):1}" ]; then
    echo "NO"
    exit 0
  fi
done

echo "YES"