How can I swap uppercase and lowercase alternatively?

前端 未结 2 1035
小蘑菇
小蘑菇 2021-01-16 12:10

I\'m writing a program that can convert uppercase into lowercase and lowercase into uppercase alternatively. Here are some examples.

abcde -> aBcDe

相关标签:
2条回答
  • 2021-01-16 13:02

    You didn't say what shell you want to use. Depending on the shell, this can be complicated or easy.

    For example, in Zsh, it is very easy:

    myvar="abcd"
    myvar_uppercase=${(U)myvar}
    
    0 讨论(0)
  • 2021-01-16 13:13

    With sed you can repeatedly parse 2 chars, changing the first in lowercase and the second in uppercase. That seems nice, but how about the last character with a string with an odd number of chars?
    First change the last char to lowercase. That is OK for an odd length string, and will be modified with the second command for an even length string:

    if [ $# -ne 1 ]; then
       exit 1
    fi
    lastcharlow=$(sed -r "s/(.)$/\l\1/" <<< "${1}")
    sed -r "s/(.)(.)/\l\1\u\2/g" <<<"${lastcharlow}"
    

    The last 2 lines can be combined:

    sed -r "s/(.)$/\l\1/; s/(.)(.)/\l\1\u\2/g" <<<"${1}"
    

    EDIT: Text beneath

    The sed solution is nice and short, but doesn't show how to loop through a string. When you really don't know a tool working for you, you can loop through your string. I will show 3 methods for changing the case of a char and two functions for looping through a string.

    function upper {
       # tr '[:lower:]'  '[:upper:]' <<< $1
       # echo "${1^^}"                     
       typeset -u up; up="$1"; echo "${up}" 
    }                                       
    
    function lower {
       # tr '[:upper:]'  '[:lower:]' <<< $1
       # echo "${1,,}"                     
       typeset -l low; low="$1"; echo "${low}" 
    }                                          
    
    function grepsolution {
       i=0
       while read -r onechar; do
          (( i++ ))
          if [[ $((i%2)) = 0 ]] ; then
              printf "%s" $(upper "${onechar}" )
          else
              printf "%s" $(lower "${onechar}" )
          fi
       done < <(echo $1 | grep -o .)
       printf "\n"
    }
    
    function substr_solution {
       i=0
       while [ $i -lt ${#1} ]; do
          (( i++ ))
          if [[ $((i%2)) = 0 ]] ; then
              printf "%s" $(upper "${1:i-1:1}" )
          else
              printf "%s" $(lower "${1:i-1:1}" )
          fi
       done
       printf "\n"
    }
    
    for teststring in abcde abcdef ABCDE ABCDEF; do
       echo "Converting ${teststring}"
       printf "%-20s: " "grepsolution"
       grepsolution "${teststring}"
       printf "%-20s: " "substr_solution"
       substr_solution "${teststring}"
    done
    
    0 讨论(0)
提交回复
热议问题