检查字符串是否是回文

时间:2014-11-04 19:08:36

标签: linux bash scripting

我正在尝试检查字符串是否是bash中的回文。以下是我提出的建议:

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

现在,echo $string|rev给出了反向字符串。我的逻辑是在if的条件下使用它。这没有那么好用。

那么,我怎样才能存储"返回值"从rev到变量? 或直接在条件下使用它?

4 个答案:

答案 0 :(得分:3)

仅限bash的实现:

is_palindrome () { 
    local word=$1
    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

灵感来自gniourf_gniourf:

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

我敢打赌这个真正递归的电话的表现真的很糟糕。

答案 1 :(得分:2)

使用$(command substitution)

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

答案 2 :(得分:2)

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

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

答案 3 :(得分:0)

也许这不是最好的实现,但是如果您只需要使用sh

#!/bin/sh

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

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

echo "YES"

以及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"