简体   繁体   English

从bash脚本中的变量添加两个字母

[英]add two letters from a variable in bash script

im working to make my code take an input (word) and output the sum of all the letters in the input, the letters would be equal to there numeric value- a=1 b=2 c=3 etc,here is my unfinished code so far:- 我正在努力使我的代码接受输入(单词)并输出输入中所有字母的总和,字母将等于那里的数值-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 = ??)

Here's a solution that uses an associative array to map (English) letters to their ordinal values. 这是一个使用关联数组将(英文)字母映射到其序数值的解决方案。 Note that associative arrays require bash 4.0 or higher . 请注意,关联数组需要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"

To iterate over the characters of a string, do this: 要遍历字符串的字符,请执行以下操作:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM