157
Program to find the duplicate words in a string
Explanation
In this program, we need to find out the duplicate words present in the string and display those words.
To find the duplicate words from the string, we first split the string into words. We count the occurrence of each word in the string. If count is greater than 1, it implies that a word has duplicate in the string.
In above example, the words highlighted in green are duplicate words.
Algorithm
- Define a string.
- Convert the string into lowercase to make the comparison insensitive.
- Split the string into words.
- Two loops will be used to find duplicate words. Outer loop will select a word and Initialize variable count to 1. Inner loop will compare the word selected by outer loop with rest of the words.
- If a match found, then increment the count by 1 and set the duplicates of word to ‘0’ to avoid counting it again.
- After the inner loop, if count of a word is greater than 1 which signifies that the word has duplicates in the string.
Solution
Python
Output:
Duplicate words in a given string : big black