我的任务是创建一个
的功能打印一个表格,表明文本中每个不同单词的出现次数与它们出现的顺序相同
我正在使用gets()
来读取字符串,这是一个标记字符串中每个单词并将其存储在二维数组中的函数,需要帮助找出如何制作分析数组的单词重复。
这是tokenizer函数:
void tokeniz(char *array)
{
char words[arraySize][arraySize] = { NULL };
const char s[2] = " ";
char *token;
int i = 0;
token = strtok(array, s);
while (token != NULL)
{
strcpy(words[i], token);
token = strtok(NULL, s);
i++;
}
wotable(words);
}
在程序的早期,我有一个函数来计算每个字符出现在字符串中的次数(预标记化)。我可以重新调整一些代码吗?
void alpha(char *array)
{
char character = 'a';
int numberOf = 0, tcc = 0;
for (character = 'a'; character <= 'z'; character++)
{
tcc = (tcc + numberOf);
numberOf = 0;
for (int i = 0; i < arraySize; i++)
if (*(array + i) == character)
numberOf++;
if (numberOf != 0)
printf("\nNumber of %c's:\t\t%d\n", character, numberOf);
}
printf("\nTotal character count:\t%d\n\n- - - - - - - - - - - - - -", tcc);
}
答案 0 :(得分:0)
不,您将无法重新调整其中一些代码。
答案 1 :(得分:0)
以下代码:
realloc()
fgets()
来取代对readline()
的调用(请务必阅读/理解readline()
的手册页)现在是代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF_LEN (1024)
struct wordsAndCount
{
char *pWord;
size_t count;
};
// note: following assumes words are not continued across multiple lines
int main( int argc, char *argv[] )
{
if( 2 != argc)
{
fprintf( stderr, "USAGE: %s <inputFileName>\n", argv[0]);
exit( EXIT_FAILURE );
}
// implied else, correct number of command line arguments
FILE *fp = NULL;
if( NULL != (fp = fopen( argv[1], "r") ) )
{ // fopen failed
perror( "fopen for input file failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
struct wordsAndCount **table = NULL;
size_t countWords = 0;
char buffer[ MAX_BUF_LEN ];
char *token = NULL;
char *delimeters = ",.;: '\"\n";
while( fgets( buffer, sizeof buffer, fp ) )
{
token = strtok( buffer, delimeters );
while( NULL != token )
{
struct wordsAndCount ** temp = realloc( table, (countWords+1)*sizeof (struct wordsAndCount *) );
if( !temp )
{ // then realloc failed
perror( "realloc failed" );
fclose( fp );
for( ; countWords; countWords-- )
{
free( (*table[countWords]).pWord );
}
free( table );
exit( EXIT_FAILURE );
}
// implied else, realloc successful
table = temp;
int foundIndex = 0;
// if word already in table[] <-- need to add code for this
(*table[foundIndex]).count++;
//else
{
(*table[countWords]).pWord = strdup( token );
if( !(*table[countWords]).pWord )
{ // then strdup failed
perror( "strdup failed" );
fclose( fp );
for( ; countWords; countWords-- )
{
free( (*table[countWords]).pWord );
}
free( table );
exit( EXIT_FAILURE );
}
// implied else, strdup successful
(*table[countWords]).count = 1;
countWords++;
}
token = strtok( NULL, delimeters );
} // end while tokens
} // end while more lines in input file
// print words and counts <-- need to add code for this
} // end function: main