How to Count The repetition of a Word in C # [duplicated]

0

Hello Good afternoon, I have tried several ways to find a way to tell the most repeated word in a sentence and I can not solve it.

Console.WriteLine("Ingrese una frase: ");
String texto =  Console.ReadLine();
  • What was the most repeated word:
  • How many times was the word repeated:
asked by Pablo 25.03.2017 в 17:08
source

2 answers

0

ok you must first use the c # Split method with the string you want to analyze and pass it as a blank parameter (""), so that this method will have an array with all the words contained in the string, and go comparing the words one by one aver which is repeated more times;

Console.WriteLine("Ingrese una frase: ");
String texto =  Console.ReadLine();
String[] palabras = texto.Split(" ");
int[] nro_repeticion_palabra = new int[palabras.Length];



 for for (int i = 0; i < palabras.Length; i++)
{
    for for (int j = 0; j < palabras.Length; j++)
    {
        if (palabras[i].compareTo(palabras[j]) == 0 )
        {
            nro_repeticion_palabra[i]++;
        }
    } 
}

now you just need to see in what position of the array (nro_repeticion_palabra) is the largest number and the value that contains that position is the number of times the word is repeated and in that same position of that array will be the word that most repeat in the array (words).

Bone without in index 3 (nro_repeticion_palabra [3] is the largest number suppose that 5 then the word that is repeated most is the one in the words [3].

It's half complicated ...

    
answered by 25.03.2017 в 22:13
0
 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Ingrese una frase: ");
        String texto = Console.ReadLine();
        String result = GetResultado(texto);
        Console.WriteLine(result);
    }

    private static string GetResultado(string linea)
    {
        IEnumerable<string> words = GetWordList(linea);

        var result = words
            .GroupBy(x => x)
            .Select(group => new { Word = group.Key, Count = group.Count() })
            .OrderByDescending(x=>x.Count).FirstOrDefault();

        return "Palabra: "+ result.Word + " Cuenta: " + result.Count;
    }

    private static IEnumerable<string> GetWordList(string linea)
    {
        return linea.Split(' ').Where(st => !st.Equals(""));
    }
}
    
answered by 25.03.2017 в 22:28