Find first repeated character

In this blog, sharing the code to find the first repeated Character in a string. Consider a String “allabouttechnologies“, here l and t are the repeated Characters but l is the first repeated Character.

str="allabouttechnologies" ## Sample String
n=${#str} ##Length of a String
PrevChar=${str:0:1} ## Set PrevChar as first character of a String
i=1
while [[ $i -lt $n ]] ## Looping through each character of a string
do
NextChar=${str:$i:1} ## Assigning NextChar equals to current Character in the Loop
if [[ $PrevChar == $NextChar ]] ## Comparing consecutive Characters of a string in a loop, if it matches,it will print repeated Character and exit the loop
then
echo $NextChar "is the first Repeating Character"
break
else
PrevChar=$NextChar ## if if doesn't matches, PrevChar Variable value is now equal to current character in a loop
fi
i=$(( $i + 1)) ## Increment the value of loop by 1
done


Related posts