Find Uncommon Characters in two Strings

In this Blog, Sharing code to find characters which are not common in the two strings. For example, String1=”iamcoder” and String2=”iamloser” has below uncommon characters .
c, d, l, s

str1="iamcoder" # String 1
str2="iamloser" # String 2
CharInStr1NtPrInStr2='' #Blank String which will have Characters in String1 which are not present in String2
CharInStr2NtPrInStr1='' #Blank String which will have Characters in String2 which are not present in String1
m=${#str2} ##Length of a String2
n=${#str1} ##Length of a String1
i=0
j=0
while [[ $i -lt $n ]] #loop through all characters of String1
do
Char=${str1:$i:1}
CharPresentInStr1=echo $str2 | grep -i $Char | wc -l #checking whether a character of String1 present in String2 or not
AlreadyPresentInNewStr=echo $CharInStr1NtPrInStr2 | grep -i $Char | wc -l #checking same Character whether is present in CharInStr1NtPrInStr2 or not to avoid duplicate Character
if [[ $CharPresentInStr1 -eq "0" && $AlreadyPresentInNewStr -eq "0" ]] #if both equates to 0 , means not present, then add Character to String CharInStr1NtPrInStr2
then
CharInStr1NtPrInStr2=${CharInStr1NtPrInStr2}${Char}
fi
i=$(( $i + 1))
done
while [[ $j -lt $m ]]
do
Char=${str2:$j:1}
CharPresentInStr2=echo $str1 | grep -i $Char | wc -l #checking whether a character of String2 present in String1 or not
AlreadyPresentInNewStr=echo $CharInStr2NtPrInStr1 | grep -i $Char | wc -l #checking same Character whether is present in CharInStr2NtPrInStr1 or not to avoid duplicate Character
if [[ $CharPresentInStr2 -eq "0" && $AlreadyPresentInNewStr -eq "0" ]] #if both equates to 0 , means not present, then add Character to String CharInStr2NtPrInStr1
then
CharInStr2NtPrInStr1=${CharInStr2NtPrInStr1}${Char}
fi
j=$(( $j + 1))
done
echo ${CharInStr1NtPrInStr2}${CharInStr2NtPrInStr1}
#Printing all uncommon Characters.



Related posts