At the entrance to the program is given the text (for example, "Hello, world! Hi"). How to make the program display only those words in which the number of characters is greater than the number, in the value of some variable?

For example, in this case ("Hello, world! Hi"), with some N = 2, the program would only output "Hello, world!".

  • It is necessary to break the input line into words, check the length of each word and, depending on the length, display it on the screen - Anton Shchyrov
  • Eh .. Not C ++ ... And then I would regex prisobachil :) - Qwertiy

2 answers 2

If the original entered string should remain unchanged, then use the standard C functions strcspn and strspn

Below is a demonstration program that is based on a solution with the specified functions.

 #include <stdio.h> #include <string.h> #define N 255 int main( void ) { const size_t M = 2; while ( 1 ) { char s[N]; printf( "Enter a sentence: (Enter - exit): " ); if ( fgets( s, N, stdin ) == NULL || s[0] == '\n' ) break; s[ strcspn( s, "\n" ) ] = '\0'; printf( "\n" ); for ( const char *first = s; *first; ) { const char *delimiter = " \t"; size_t m = strspn( first, delimiter ); first += m; m = strcspn( first, delimiter ); if ( M < m ) printf( "%*.*s ", m, m, first ); first += m; } printf( "\n" ); } return 0; } 

The output of the program to the console may look as follows.

 Enter a sentence: (Enter - exit): Hello, world! Hi Hello, world! Enter a sentence: (Enter - exit): 

That is, the first query introduced the string Hello, world! Hi Hello, world! Hi , and during the second query, the Enter key was simply pressed without entering data to stop the loop.

You can change the program so that the value of the minimum word length is also entered by the user through the console.

    Break the input into words, and throw away short ones. Use, for example, the function strtok for word splitting. Something like:

     int main(int argc, const char * argv[]) { char buf[1024], *s; int N; printf("Введите строку: "); fgets(buf,1024,stdin); printf("Введите порог: "); scanf("%d",&N); for(s = strtok(buf," \t\n"); s; s = strtok(NULL," \t\n")) { if (strlen(s) > N) printf("%s ",s); } puts(""); } 
    • Is it possible to do the same without using string.h? - Arden
    • It is possible, but then you need your own function to select words from a string, and even determine the length of a string :) - Harry
    • @Arden, you can, but it makes sense to reinvent the wheel with square wheels the size of a truck? - PinkTux 2:53