我在bash中written up是一个'挂人'型游戏。目前正在工作,但我无法理解如何覆盖字符串中的某些字符。
所以目前我从用户那里收到一封信(例如'l'),并根据字符串'hello'进行检查,并打印出'_ _ ll _'(代码中{$prev
)我想当用户输入'e'时,$prev
更新为'_ ell _'等等等等等等'h'和'o'。
问:我如何更改字符串中的某个字符?
答案 0 :(得分:0)
如果要操作变量中的单个字符,则更容易将所有字符保存在数组中。这样您就可以根据数组索引更改字符。下面显示了在操作字符时转换为数组或从数组转换的简单方法。注意:无需转换回变量,只需在数组中保持猜测的单词:
#!/bin/bash
declare -a array
prev="__||_" ## previous state of guessing
printf "%s\n" "$prev"
for ((i=0; i<${#prev}; i++)); do ## convert to array
array+=( ${prev:i:1} )
done
array[1]="e" ## update letter
## convert back to string
printf -v prev $(echo ${array[@]} | tr -d ' ')
printf "%s\n" "$prev"
<强>输出强>
$ bash ~/scr/tmp/stack/strtoarray.sh
__||_
_e||_
答案 1 :(得分:0)
使用数组作为单词和答案的hangman实现。它从$ {words}指向的文件中选择一个随机单词。
#!/usr/bin/env bash
words='/usr/share/dict/words'
die() { >&2 echo $@; exit 1; }
join() { local IFS="$1"; shift; echo "$*"; }
new_word() {
unset word
local length=$(wc -l < ${words})
local count=$((${RANDOM} % ${length}))
head -${count} ${words} | tail -1 | tr '[:upper:]' '[:lower:]'
}
draw_hangman() {
# draw hangman here
((++guesses))
}
[[ -f ${words} ]] || die "Missing words file: ${words}"
declare -i guesses=0
declare -a word=( $(new_word | grep -o .) )
declare -a answer=( $(printf '_ %.0s' $(seq 1 ${#word[@]})) )
while :; do
echo -e "\nPress - to quit.\n"
echo -e "${answer[@]}\n"
read -s -n 1 -p "$((${#word[@]} - ${guesses})) more guesses: " guess
echo
[[ ${guess} == '-' ]] && echo && break # quit
[[ ${guesses} -eq $((${#word[@]} - 1)) ]] && echo -e "\nYOU LOSE!\n" && \
echo "The word was $(join '' ${word[@]})" && break
[[ ${word[@]} != *${guess}* ]] && draw_hangman && continue
for i in ${!word[@]}; do
[[ ${word[${i}]} == ${guess} ]] && answer[${i}]=${guess}
done
[[ ${answer[@]} == ${word[@]} ]] && echo -e "\nYOU WIN!\n" && break
done