我一直在學習 Bash,我的老師做了一個讓我感到困惑的練習。
我只是在努力在單詞前面添加空格。
代碼應考慮每個單詞中的字符數,并調整星號和間距的數量以使其始終對齊。
它應該是這樣的:
***********
* Hello *
* World *
* good *
* etceter *
***********
我的代碼:
#determine biggest word
words=("Hello" "World" "good" "etceter")
numchar=0
for i in ${words[@]}; do
if [ ${#i} -gt $numchar ]
then
numchar=${#i}
fi
done
#write *
a=-4
while [ $a -lt $numchar ]; do
printf "*"
((a ))
done
#write array
echo
for txt in ${words[@]}; do
space=$(($numchar-${#txt}))
s=0
echo "* $txt "
while [ $s -lt $space ]; do
printf " "
((s ))
printf "*"
done
done
#write *
a=-4
while [ $a -lt $numchar ]; do
printf "*"
((a ))
done
我正在為 #write 陣列部分苦苦掙扎。
提前謝謝了!
uj5u.com熱心網友回復:
您只需要進行一些更改。
#write array
echo
for txt in ${words[@]}; do
space=$(($numchar-${#txt}))
s=0
echo -n "* $txt " # -n added to not append a newline
while [ $s -lt $space ]; do
echo -n " " # switched from printf to echo (cosmetics)
((s ))
# printf "*" # commented out
done
echo "*" # added
done
您的while回圈僅在當前單詞之后添加空格。尾隨*出現在回圈之后以完成此行。
uj5u.com熱心網友回復:
重寫最后 3 個部分:
# define solid string of asterisks
printf -v stars '*%.0s' $(seq 1 $(( numchar 4)) ) # length = numchar 4
echo "${stars}"
for txt in "${words[@]}"
do
printf "* %-*s *\n" "${numchar}" "${txt}"
done
echo "${stars}"
這會產生:
***********
* Hello *
* World *
* good *
* etceter *
***********
uj5u.com熱心網友回復:
你是在正確的軌道上首先獲得最長線的長度。
邊框和填充可以完全使用printf格式說明符和模式替換來完成。用于%-Ns左%Ns對齊和右對齊。
通過正確參考,您還可以在每行中包含多個單詞和空格。
下面是一個例子:
lines=('Hello World!'
'Line two.'
a-line
'another line'
'The end.')
# border character
c='*'
# get length of longest line, required for padding
for i in "${lines[@]}"; do
((${#i} > pad)) &&
pad=${#i}
done
# make a string to fill top/bottom
fill=$(printf %$((pad 4))s "$c")
fill=${fill// /$c}
# print the text box
printf '%s\n' "$fill"
for line in "${lines[@]}"; do
printf "$c %-${pad}s $c\n" "$line"
done
printf '%s\n' "$fill"
輸出:
****************
* Hello World! *
* Line two. *
* a-line *
* another line *
* The end. *
****************
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342682.html
上一篇:無法將二維陣列傳遞給C 中的函式
下一篇:陣列索引導致越界
