checking if a string is a palindrome

后端 未结 4 425
难免孤独
难免孤独 2021-01-14 19:40

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 ==         


        
相关标签:
4条回答
  • 2021-01-14 20:22

    A bash-only implementation:

    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
    

    Inspired by 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.

    0 讨论(0)
  • 2021-01-14 20:25

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

    #!/bin/bash
    read -p "Enter a string: " string
    if [[ $(rev <<< "$string") == "$string" ]]; then
        echo Palindrome
    fi
    
    0 讨论(0)
  • 2021-01-14 20:37

    Maybe it is not the best implementation, but if you need something with pure 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"
    

    and canonical way with bash as well

    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"
    
    0 讨论(0)
  • 2021-01-14 20:40

    Use $(command substitution):

    #!/bin/bash
    read -p "Enter a string: " string
    if [[ "$(echo "$string" | rev)" == "$string" ]]; then
        echo "Palindrome"
    fi  
    
    0 讨论(0)
提交回复
热议问题