reverse the order of characters in a string

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

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

13条回答
  •  被撕碎了的回忆
    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... ;)

提交回复
热议问题