Given a line of text in which words are separated by spaces and commas. Necessary: ​​Determine the number of words with a length of 3 characters

#include <iostream> #include <conio.h> #include <string> using namespace std; int countWords(string st) { int count = 0; for (int i=0; i<st.size(); i++) { if (st[i] == ' ') count++; } return count; } int main() { string st = "\n So she was considering in her own mind, as well as she could, for the hot day made her feel very sleepy and stupid, whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her."; cout<<st; cout<<"\n\n The string has "<<countWords(st)<<" words of tres characters."; _getch(); } 

I just know how to find the number of words, can you help me please.

  • If there is no space after the comma, then you will count the number of words incorrectly. - LEQADA
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

5 answers 5

Such tasks must be broken apart.

First write a function that simply goes through the words and finds their length.

 int next_word_length(const char*& str) { // пропускаем пробелы и пунктуацию while (*str != '\0' && !std::isalpha(*str)) ++str; // проверяем что строка не закончилась if (*str == '\0') return 0; int len = 0; // вычисляем длину слова while (std::isalpha(*str)) { ++len; ++str; } return len; } 

Then write a code that using this function displays words with a length of 3

 #include <iostream> #include <string> #include <cctype> int next_word_length(const char*& str); int main() { const char* str = "\n So she was considering in her own mind, as well as she could, for the hot day made her feel very sleepy and stupid, whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her."; int word_count = 0; while (int len = next_word_length(str)) { if (len == 3) { ++word_count; std::cout << std::string(str - len, str) << '\n'; // для отладки } } std::cout << "Words with len==3 : " << word_count << '\n'; } 

    It would be correct to consider punctuation marks, not just a space or comma, since your sentence also contains a period in addition to these signs, and the last word of 3 characters ends with a period.

     ...by her."; ^^^ 

    The function may look like this, as shown in the demo program below (I added a dot character to delimiters, although, as I wrote, it would be better to use any punctuation as a delimiter)

     #include <iostream> #include <string> const std::string::size_type TARGET_LENGTH = 3; std::string::size_type countWords( const std::string &s, std::string::size_type length = TARGET_LENGTH ) { const char *delimiter = " ,."; std::string::size_type count = 0; std::string::size_type pos = 0; while ( ( pos = s.find_first_not_of( delimiter, pos ) ) != std::string::npos ) { std::string::size_type n = s.find_first_of( delimiter, pos ); if ( n == std::string::npos ) n = s.size(); count += n - pos == length; pos = n; } return count; } int main() { std::string s = "\n So she was considering in her own mind, as well as she could, for the hot day made her feel very sleepy and stupid, whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her."; std::cout << '[' << s << ']' << std::endl; std::cout <<"\n\n The string has " << countWords( s ) << " words of " << TARGET_LENGTH << " characters." << std::endl; } 

    Its output to the console

     [ So she was considering in her own mind, as well as she could, for the hot day made her feel very sleepy and stupid, whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.] The string has 17 words of 3 characters. 

      I suggest the following implementation of the countWords function

       int countWords(string st) { int count = 0; int currentLengthWord = 0; for (int i = 0; i< st.size(); i++) { // проверяем, не конец ли это слова(здесь мы перечисляем любые символы, которые являются разделителем слова) if (st[i] != ' ' && st[i] != '!' && st[i] != '.' && st[i] != ',' && st[i] != '?' && st[i] != ':') { currentLengthWord++; } else { // конец слова, проверяем ее длину(равна ли 3) if(currentLengthWord == 3) { // длина слова равна 3, инкрементируем счетчик количества слов ++count; } currentLengthWord = 0; } } // проверяем конец текста, если последнее слово также равно 3, то также инкрементируем if(currentLengthWord == 3) ++count; return count; } 
      • Mr., who minus, please leave your explanatory comment, the code is quite working in my opinion, what is wrong in it? - Alexcei Shmakov
      • eh, you, unlike me, provided for the end of the line :) +1 - dirkgntly

      Here, quite, working option

        int position = 0; for(int i = 0; i<st.size(); i++) { if(st[i]!=',' && st[i]!=' ') ++position; else { if(position == 3) ++count; position = 0; } } if(position == 3) ++count; 
      • one
        check if we send a text that contains, for example, a word of 6 letters, then your algorithm will find two words of 3 letters, although in fact, in this case, there is not a single word of 3 letters - Alexcei Shmakov
      • @AlexceiShmakov again you are right, thanks for editing :) - dirkgntly

      Yes, there are often questions (most likely training questions) in which you need to pull out words (or numbers) separated from each other by various separators from a file (or lines) and then do something with them (in your case, determine the length and count the number of with a length of 3).

      Here is a very simple little function that selects the next word from the line and allows you to simplify the solution to the mass of similar problems.

       #include <stdio.h> #include <string.h> /* before call: *p -- ptr to start search WORD in delimiters after call: *p -- ptr to next char after word (and *p - word == WORD length) returns ptr to WORD or 0 */ char * strtos (char **p, const char *delim) { char *word = 0; if (*((*p) += strspn(*p, delim))) { word = *p; (*p) += strcspn(*p, delim); } return word; } 

      To understand how it works, just read man strspn .

      How you can use it (Linux, file c1.c)
      (I apologize, I messed up a bit (inattentively read the question), in your case you only need an internal cycle, after which you print the meter and discard it, and you can consider the external one as a test strapping)

       #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { // предполагаем, что strtos оттранслирована gcc -c strtos.c #endif // по хорошему все это д.б. в каком-нибудь подключаемом strtos.h файле char *strtos (char **start_lookup, const char *delimiters_str); #ifdef __cplusplus }; #endif #define SEP " ,\n" // допустим, что слово все же не может переходить со строки на строку //#define SEP " \t\n\"\'.,;:+-*/(){}[]=?!~%^&\\" // а это для Си текстов (наверняка что-то упустил) int main (int ac, char *av[]) { size_t lsize, wlen, n3 = 0; char *curline = 0, *start, *word; while ((getline(&curline, &lsize, stdin) > 0) && (start = curline)) while (word = strtos(&start, SEP)) n3 += (start - word == 3); return printf("%ld 3-length words\n", (long)n3) < 0; } 

      Those. read the file line by line, alternately pull out words (separated by one or more separators (space, comma)) from the read line, and if the word length is three, increment the counter.

      We broadcast and run

       avp@avp-ubu1:hashcode$ g++ c1.c strtos.o ; ./a.out <c1.c 7 3-length words avp@avp-ubu1:hashcode$ 

      If something is not clear, ask in the comments (mentioning @avp, I won't get a notification without a dog).