如何将字数和字符数返回到一个数组中?
#define NUMBER_MOVIES 3
void getWordCount( char movies[NUMBER_MOVIES][40]);
int main ()
{
char movies[NUMBER_MOVIES][40] = {"Jurasic World", "Captain America", "I spite on your grave"};
getWordCount(movies);
return 0;
}
void getWordCount(char movies[NUMBER_MOVIES][40])
{
int i;
int wordCount = 0;
int wordCharCount[ ]; // need to store to this array
for(i = 0; i < strlen(movies[i]); i++)
{
if (*movies[i] == ' ')
{
wordCount++;
printf ("word count :%s, %d \n", movies[i], wordCount);
}
printf ("word count :%s, %d \n", movies[i], wordCount);
}
}
我想将所有单词计数和字符计数存储到同一数组中,即wordCharCount []
例如:侏罗纪世界;数组应为[2 8 5]。因此2个单词和第一个单词包含8个字符,第二个单词包含5个字符。另外,应该可以从函数外部访问array。
答案 0 :(得分:0)
最明显的问题是您的字数只有一个循环,但是您需要扫描每部电影中的每个字符-这建议两个嵌套循环。
那么在单个数组中返回两种信息的想法是不明智的-结构会更合适。然后,在C语言中,您无法按值传递或返回数组,因此通常使调用者按引用传递数组以使函数放置结果。
考虑:
#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]++ ;
}
}
}
}
输出:
"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