reverse the order of characters in a string

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

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

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

    Some simple methods of reversing a string

    echo '!!!esreveR si sihT' | grep -o . | tac | tr -d '\n' ; echo
    
    echo '!!!esreveR si sihT' | fold -w 1 | tac | tr -d '\n' ; echo
    

    Convert to hex values then reverse

    echo '!!!esreveR si sihT' | xxd -p | grep -o .. | tac | xxd -r -p ; echo
    
    echo '!!!esreveR si sihT' | xxd -p | fold -w 2 | tac | xxd -r -p ; echo
    
    0 讨论(0)
  • 2020-12-04 15:47

    Simple:

    var="12345"
    copy=${var}
    
    len=${#copy}
    for((i=$len-1;i>=0;i--)); do rev="$rev${copy:$i:1}"; done
    
    echo "var: $var, rev: $rev"
    

    Output:

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

    A bash solution improving over @osdyng answer (my edit was not accepted):

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

    Or an even simpler (bash) loop:

    var=$1   len="${#var}"   i=0   rev=""
    
    while (( i<len )); do rev="${var:i++:1}$rev"; done
    
    echo "var: $var, rev: $rev"
    

    A POSIX solution:

    var="12345"     rev=""    i=1
    
    while  [ "$i" -le "${#var}" ]
    do     rev="$(echo "$var" | awk -v i="$i" '{print(substr($0,i,1))}')$rev"
           : $(( i+=1 ))
    done
    
    echo "var: $var, rev: $rev"
    

    Note: This works on multi byte strings. Cut solutions will work only in ASCII (1 byte) strings.

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

    I know you said "without third-party tools", but sometimes a tool is just too obviously the right one, plus it's installed on most linux systems by default:

    [madhatta@risby tmp]$ echo 12345|rev
    54321
    
    0 讨论(0)
  • 2020-12-04 15:49

    rev | tail -r (BSD) or rev | tac (GNU) also reverse lines:

    $ rev <<< $'12\n34' | tail -r
    43
    21
    $ rev <<< $'12\n34' | gtac
    43
    21
    

    If LC_CTYPE is C, rev reverses the bytes of multibyte characters:

    $ LC_CTYPE=C rev <<< あの
    ��め�
    $ export LC_ALL=C; LC_ALL=en_US.UTF-8 rev <<< あの
    のあ
    
    0 讨论(0)
  • 2020-12-04 15:49

    Here is another simpler awk solution:

    awk 'BEGIN{FS=""} {for (i=NF; i>0; i--) s=s $i; print s}' <<< '123456'
    

    654321
    
    0 讨论(0)
提交回复
热议问题