passing letters from an array into a string for string comparison

attempting the hangman program. This was an optional assignment from the professor. I have completed the logical coding, debugging now.

##I have an array $wordString[] that initializes to a string of dashes
##reflecting the number of letters in $theWord
##every time the user enters a (valid) letter this function is called and $letter is passed to it as $1
function updateWordString()
{
for ((x=1;x <= $numberOfLettersInTheWord;x++))
do
currentLetter=$(echo $theWord|head -c $x|tail -c 1)
if [ "$1" == "$currentLetter" ]
then
wordString[$x]="$currentLetter"
fi
done
}

##The problem now is that i have an array that look like "f o o b a r"
##So when i want to test in the following function if the user has completed
## the word, in essence its testing if "foobar" == "f o o b a r"

function isGameOver()
{
if [ "$theWord" == "${wordString[*]}" ]
then
return 2
fi
}

touro nyc, msis616 Prof Robinson

Thanks

Since this is an assignment, here's a hint (assuming you are using either kshell or bash)

a="keeping up with the Jones"
echo "${a// /}"

If you are unfamiliar with this form of variable expansion, have a peek at the Kshell/bash doc and search for 'parameter //pattern /string'
man/man1/ksh.html man page

1 Like

Booyah! I got it to work. Thank you.

I was able to make it work like this:
tempWordString1=${wordString[*]}
tempWordString2="${tempWordString1// /}"

and then testing if [ "$theWord" == "$tempWordString2" ]

I was not able to get it to work like this:
tempWordString="${${wordString[*]}// /}"
i tried playing with the syntax (pulling out $, adding " ")but couldn't get it to work. Is there a way to do parameter expansion directly on an array?

Again, thank you.

Glad it worked, you discovered what I was thinking of (assigning it to a tmp variable and testing against that after removing blanks).

I also tried something similar to your other efforts, ${arrayname[@]// /}] , and that fails. Actually it succeeds, but not in the way you wanted. The substitution is applied to each element as they are echoed, and not to the overall expansion as a whole. I also thought that setting the field separator might work, but alas that failed too.

So, best I can tell, no there isn't a way to apply it directly. Maybe somebody else round here might know better.

the man page was useful.

Thread closed