2つの文字列を比較した後の残りの文字

2つの文字列を比較した後の残りの文字

私は現在、ユーザー入力とコンピュータ入力を比較するbashゲームを書いています。

2つの文字列を比較した後に残りの文字を探したいです。私の考えは次のとおりです。

user_word='hello' 

computer_word='bxolq' 

compare  ${user_word} ${computer_word} 

compare function: (finds "l" to be equal in the two strings)

calculate leftover word for user (= "heo") 

calculate leftover word for computer (= "bxoq")

"bxoq"長さが4で、ユーザーの残りの数が3なので、コンピュータが勝ちます"heo"

この問題を解決しようとしましたが、diff結果は

diff <(echo ${user_word} | sed 's:\(.\):\1\n:g' | sort) <(echo ${computer_word} | sed 's:\(.\):\1\n:g' | sort)

私を混乱させる。

だから私の質問は:残りの比較をどのように完了できますか?

ベストアンサー1

シェルでは、文字を削除する文字列がどこにあり、削除する特定の文字セットがどこにあるかを使用して、文字列の文字セット内bashで発生したすべての文字を削除できます。セットは、文字セットの 1 つの文字に一致する、または類似した一般的なシェル パターン角かっこ式です。${variable//[set]/}variable[set][abcd][a-g0-5]

置換はbashセット内のすべての文字を一致させ、何もない文字に置き換えます(つまり削除)。

コードでこれを使用して、ある文字列内のすべての文字を別の文字列から削除したり、その逆を削除したりできます。

$ user_word='hello' comp_word='bxolq'
$ echo "${user_word//["$comp_word"]/}"
he
$ echo "${comp_word//["$user_word"]/}"
bxq

次に使用する関数は拡張で${#variable}、変数に格納された文字列の文字数を知らせますvariable

$ short_user_word=${user_word//["$comp_word"]/}; suw_len=${#short_user_word}
$ short_comp_word=${comp_word//["$user_word"]/}; scw_len=${#short_comp_word}
$ if [ "$scw_len" -lt "$suw_len" ]; then echo 'User won'; elif [ "$scw_len" -gt "$suw_len" ]; then echo 'Computer won'; else echo 'It is a draw'; fi
Computer won

引数から2つの単語を取得するスクリプト:

#!/bin/bash

user_word=$1
comp_word=$2

short_user_word=${user_word//["$comp_word"]/}; suw_len=${#short_user_word}
short_comp_word=${comp_word//["$user_word"]/}; scw_len=${#short_comp_word}

if [ "$scw_len" -lt "$suw_len" ]; then
    echo 'User won'
elif [ "$scw_len" -gt "$suw_len" ]; then
    echo 'Computer won'
else
    echo 'It is a draw'
fi

おすすめ記事