There is a class in which the method should output the number of words consisting of n characters from a text file.

//Открывает файл private async void ButtonBrowse_Click(object sender, RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".txt"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { LabelPath.Text = file.Path; TextFile.Text = await Windows.Storage.FileIO.ReadTextAsync(file); } else { // } } private void ButtonCount_Click(object sender, RoutedEventArgs e) { LabelNCount.Text = "Number of n-count words: " + CountClass.nCount(TextFile.Text, Int32.Parse(TextNCount.Text)); } //Метод из класса CountClass, в котором должен происходить подсчёт public static int nCount(String file, int numberOfCharacters) { return file.Split('\n').Count(line => line.Length > numberOfCharacters); //это или не работает, или лыжи не едут } 

There are no problems with counting all the words in the file. But how to count words of a certain length?

  • The nCount method displays the number of lines in the file, but not the number of words. Only if you have one word in the file in one line. \n - move to a new line. - Denis Bubnov
  • In addition to what was written above, you are looking for the number of lines with more characters than numberOfCharacters and not equality. - Ev_Hyper
  • @Ev_Hyper, yes for sure, overlooked. - Alexandr Smushko
  • What then can I use to find the words I need? - Alexandr Smushko

1 answer 1

Find the number of words of the required length somehow like this:

 public int GetCountWordsByLength(string text, int length) { char[] delimiters = new char[] { ' ', '\r', '\n', ',', '?', '-' }; // разделители var words = text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); // все слова return words.Where(x => x.Length == length).ToList().Count; // количество слов по условию } 

Well, the method call:

 string text = "я веселный молочник\n кто сказал, что я один?"; var count = GetCountWordsByLength(text, 3); // количество слов длинной в 3 символа 
  • Thank. Just correct it with return words.Where(x => x.Length == length).ToList().Count - Alexandr Smushko
  • one
    @AlexandrSmushko, then the type of the return value to 'int') is not at all, here the main line of thought) 'Count' can be added to the variable) I’ll fix it now - Denis Bubnov