Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I make a program that checks if there is 2 of the same word. For example if I have a text: "the elephant jumps on the ball". It is two " the " in the text and what I want is that the program should tell me when there is 2 of the same word... I have no clue how to do this.
Thank you.
Posted
Updated 8-Oct-10 9:22am
v2

Maybe take the text and bubble sort it.
Then loop through and see where any word is followed by the same word.
Highlight that word and Bingo!
 
Share this answer
 
Example:

string input = "the elephant jumps on the ball".ToLower();

string[] words = input.Split(' ','.',',');

List<string> unikWords = new List<string>();
List<int> count = new List<int>();

foreach (string value in words)
{
if (unikWords.Contains(value))
{
int p = unikWords.IndexOf(value);
count[p]++;
}
else
{
unikWords.Add(value);
count.Add(1);
}
}

for (int i = 0; i < unikWords.Count; i++)
{
if (count[i] > 1)
MessageBox.Show(unikWords[i]+","+count[i].ToString());
}
 
Share this answer
 
C#
Dictionary<string,int> dict= new Dictionary<string,int>();
string str = "the elephant jumps on the ball";
string [] a = str.Split(new char []{' '});
foreach( string s in a)
{
  if (dict.ContainsKey(s) )
     dict[s]++;
  else
     dict[s]=1;
}
foreach(string k in dict.Keys)
{
  if (dict[k] == 2) Console.WriteLine(k);
}

:)
 
Share this answer
 
Comments
euhiemf 9-Oct-10 3:49am    
This works perfect!!! Thank you!
CPallini 9-Oct-10 4:31am    
You are welcome. :-)
A first attempt would be just to split every line in words and then sort the resulting list. After that you just loop over the list and check if a word is followed once or more times by itself..

Maybe not very efficient, but quite easy.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900