一个天真的解决方案可能会一次读取一个字符,当它是'U'
,时'I'
,'N'
或者'K'
然后读取另一个字符以查看它是否是组中的下一个字符。如果是,则为该组增加一个计数器。所有其他字符都被简单地丢弃。
编辑:示例函数:
int count_uu = 0;
int count_ii = 0;
int count_nj = 0;
int count_ku = 0;
void check_next_char(int expected, FILE *input, int *counter);
void count(FILE *input)
{
int ch; /* Character we read into */
while ((ch = fgetc(input)) != EOF)
{
switch (ch)
{
case 'U':
check_next_char('U', input, &count_uu);
break;
case 'I':
check_next_char('I', input, &count_ii);
break;
case 'N':
check_next_char('J', input, &count_nj);
break;
case 'K':
check_next_char('U', input, &count_ku);
break;
default:
/* Not a character we're interested in */
break;
}
}
/* This function gets the next character from a file and checks against
an `expected` character. If it is same as the expected character then
increase a counter, else put the character back into the stream buffer */
void check_next_char(int expected, FILE *input, int *counter)
{
int ch = fgetc(input);
if (ch == expected)
(*counter)++;
else
ungetc(ch, input);
}