How to find all the words that are repeated in the .txt file and display them on the screen?
Closed due to the fact that the participants are not on topic by default locale , andreymal , Cheg , pavel , Kromster 24 Sep '17 at 18:36 .
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
- "The message contains only the text of the task, in which there is no description of the problem, or the question is purely formal (" how do I do this task ") . To reopen the question, add a description of the specific problem, explain what does not work, what you see the problem. " - default locale, andreymal, Cheg, pavel
- oneSample file at least indicated - EvgeniyZ
- @EvgeniyZ 1 1 2 3 4 - Unknown
|
3 answers
File.ReadAllText("file.txt") .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .GroupBy(w => w) .Where(w => w.Count() > 1) .Select(w => w.Key) .ToList() .ForEach(Console.WriteLine); - 3It looks beautiful. - Nick Volynkin ♦
|
You can for example like this:
string[] input = "1 1 1 2 3 4".Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //string[] input = File.ReadAllText("file.txt").Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string[] output = (from word in input where Array.IndexOf(input, word) != Array.LastIndexOf(input, word) select word).Distinct().ToArray(); |
var hash = new HashSet<string>(); var strings = File.ReadAllText("file.txt") .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .Where(x => !hash.Add(x)).Distinct().ToArray(); foreach (var s in strings) { Console.WriteLine(s); } The HashSet<>.Add() method returns false if the item is already in the collection.
- It is also necessary to take into account the variant in which the repeating element will occur, for example, 5 times. Your code in this case will display it 4 times. Something like
Distinctneeds to be done ... - Andrey NOP - @ Andrei yes, for sure - RusArt
- By the way, another interesting option is to start another
HashSetand add to it all elements that were not added to the first one - this will be repeated + without duplicates at once. Maybe it will work faster - Andrew NOP - one@Andrey
Distinctdoes it inside - RusArt - Yes, indeed, looked the source - Andrew NOP
|