我正在努力使我的代码获取输入(word)并输出输入中所有字母的总和,字母将等于那里的数值-a = 1 b = 2 c = 3等,这里是到目前为止我未完成的代码: -
echo enter word
read word
for let in $word
do
echo $let
*here is where it should take the input and calculate the output (w+o+r+d = ??)
答案 0 :(得分:1)
这是一个使用关联数组将(英文)字母映射到其序数值的解决方案。请注意,关联数组需要 bash 4.0或更高版本。
#!/usr/bin/env bash
# Declare variables.
declare -i i sum # -i declares integer variables
declare -A letterValues # -A declares associative arrays, which requires bash 4+
declare letter # a regular (string) variable
# Create a mapping between letters and their values
# using an associative array.
# The sequence brace expression {a..z} expands to 'a b c ... z'
# $((++i)) increments variable $i and returns the new value.
i=0
for letter in {a..z}; do
letterValues[$letter]=$((++i))
done
# Prompt for a word.
read -p 'Enter word: ' word
# Loop over all chars. in the word
# and sum up the individual letter values.
sum=0
for (( i = 0; i < ${#word}; i++ )); do
# Extract the substring of length 1 (the letter) at position $i.
# Substring indices are 0-based.
letter=${word:i:1}
# Note that due to having declared $sum with -i,
# surrounding the following statement with (( ... ))
# is optional.
sum+=letterValues[$letter]
done
# Output the result.
echo "Sum of letter values: $sum"
答案 1 :(得分:0)
要迭代字符串的字符,请执行以下操作:
string="hello world"
for ((i=0; i < ${#string}; i++)); do
char=${string:i:1} # substring starting at $i, of length 1
echo "$i -> '$char'"
done
0 -> 'h'
1 -> 'e'
2 -> 'l'
3 -> 'l'
4 -> 'o'
5 -> ' '
6 -> 'w'
7 -> 'o'
8 -> 'r'
9 -> 'l'
10 -> 'd'