[Solved] How to count total number of words and count characters of each word in a given string and create 1D array? [closed]


The most obvious problem is your word count only has a single loop, but you need to scan every character in every movie – that suggests two nested loops.

Then the idea of returning two types of information in a single array is ill-advised – a structure would be more appropriate. Then in C you cannot pass or return arrays by value, so it is usual to have the caller pass an array by reference for the function to place the results.

Consider:

#include <stdio.h>
#include <string.h>

struct sMovie
{
    char title[40] ;
    int title_stats[40] ;
} ;

void getWordCount( struct sMovie* movies, int number_of_movies );

int main ()
{
    struct sMovie movies[] = { {"Jurassic World"}, 
                               {"Captain America"}, 
                               {"I spit on your grave"} } ;

    const int number_of_movies = sizeof(movies) / sizeof(*movies) ;
    getWordCount( movies, number_of_movies ) ;

    for( int m = 0; m < number_of_movies; m++ )
    {
        printf( "\"%s\" has %d words of lengths",
        movies[m].title,
        movies[m].title_stats[0] ) ;
        for( int w = 1; w <= movies[m].title_stats[0]; w++ )
        {
            printf( " %d", movies[m].title_stats[w] ) ;
        }
        printf( "\n" ) ;
    }

    return 0;
}

void getWordCount( struct sMovie* movies, int number_of_movies )
{
    // For each movie...
    for( int m = 0; m < number_of_movies; m++)
    {
        memset( movies[m].title_stats, 0, sizeof(movies[m].title_stats) ) ;
        movies[m].title_stats[0] = 1 ;

        // For each character
        for( int i = 0; movies[m].title[i] != 0; i++ )
        {
            int word = movies[m].title_stats[0] ; 
            movies[m].title_stats[word]++ ;

            if( movies[m].title[i] == ' ' )
            {
                movies[m].title_stats[word]-- ;
                movies[m].title_stats[0]++ ;
            }
        }
    }
}

Output:

"Jurassic World" has 2 words of lengths 8 5                                                                                                              
"Captain America" has 2 words of lengths 7 7                                                                                                             
"I spit on your grave" has 5 words of lengths 1 4 2 4 5                                                                                                  

7

solved How to count total number of words and count characters of each word in a given string and create 1D array? [closed]