reverse the order of characters in a string

后端 未结 13 980
逝去的感伤
逝去的感伤 2020-12-04 15:03

In string \"12345\", out string \"54321\". Preferably without third party tools and regex.

相关标签:
13条回答
  • 2020-12-04 15:34

    read word

    reve=`echo "$word" | awk '{for(i=length($0); i>0;i--) printf (substr($0,i,1));}'`
    echo  "$reve"
    
    0 讨论(0)
  • 2020-12-04 15:37

    This reverses the string "in place":

    a=12345
    len=${#a}
    for ((i=1;i<len;i++)); do a=$a${a: -i*2:1}; done; a=${a:len-1}
    echo $a
    

    or the third line could be:

    for ((i=0;i<len;i++)); do a=${a:i*2:1}$a; done; a=${a:0:len}
    

    or

    for ((i=1;i<len;i++)); do a=${a:0:len-i-1}${a: -i:i+1}${a:len-i-1:1}; done
    
    0 讨论(0)
  • 2020-12-04 15:38

    If var=12345:

    bash for((i=0;i<${#var};i++)); do rev="$rev${var:~i:1}"; done

    sh c=$var; while [ "$c" ]; do rev=$rev${c#"${c%?}"}; c=${c%?}; done

    echo "var: $var, rev: $rev"
    

    Run it:

    $ rev
    var: 12345, rev: 54321
    
    0 讨论(0)
  • 2020-12-04 15:41

    Presume that a variable 'var' has the value '123'

    var="123"
    

    Reverse the string and store in a new variable 'rav':

    rav=$(echo $var | rev)
    

    You'll see the 'rav' has the value of '321' using echo.

    echo $rav
    
    0 讨论(0)
  • 2020-12-04 15:42

    For those without rev (recommended), there is the following simple awk solution that splits fields on the null string (every character is a separate field) and prints in reverse:

    awk -F '' '{ for(i=NF; i; i--) printf("%c", $i); print "" }'
    

    The above awk code is POSIX compliant. As a compliant awk implementation is guaranteed to be on every POSIX compliant OS, the solution should thus not be thought of as "3rd-party." This code will likely be more concise and understandable than a pure POSIX sh (or bash) solution.

    (; I do not know if you consider the null string to -F a regex... ;)

    0 讨论(0)
  • 2020-12-04 15:43

    This can of course be shortened, but it should be simple to understand: the final print adds the newline.

    echo 12345 | awk '{for (i = length($0); i > 0; i--) {printf("%s", substr($0, i, 1));} print "";}'
    
    0 讨论(0)
提交回复
热议问题