请原谅我没有使用伪代码,而是使用了实际代码。我希望我现在能很好地理解这个问题,以至于我认为它看起来并不复杂,是准确的。
# include <stdio.h>
# include <ctype.h>
# include <string.h>
# define BUFF_SIZE 1024
# define WORD_DELIM " "
# define MATCH_PATT "barf"
int main( int ac , char *av[] )
{
__u_char false = ( 1 == 0 ) ;
__u_char true = ( 1 == 1 ) ;
__u_char match_1_back = false ;
__u_char match_2_back = false ;
char line_buff[ BUFF_SIZE ] ;
char *buff_ptr ;
char *word_ptr ;
while ( fgets( line_buff , BUFF_SIZE , stdin ) )
{
puts( "\nInput line was: " ) ;
puts( line_buff ) ;
puts( "Output line is: " ) ;
buff_ptr = line_buff ;
while ( ( word_ptr = strtok( buff_ptr , WORD_DELIM ) ) != NULL )
{
buff_ptr = NULL ;
if ( strcmp( word_ptr , MATCH_PATT ) == 0 )
{
// Set these to what they should be for next iteration.
match_2_back = match_1_back ;
match_1_back = true ;
// Don't output matched token.
}
else
{
// Don't output token if a token matched 2 tokens back.
if ( ! match_2_back )
printf( "%s " , word_ptr ) ;
// Set these to what they should be for next iteration.
match_2_back = match_1_back ;
match_1_back = false ;
}
}
printf( "\n" ) ;
}
}
使用此输入:
barf barf barf healthy feeling better barf barf barf uh oh sick again
barf barf healthy feeling better barf barf uh oh sick again
barf healthy barf feeling better barf uh barf oh sick again
barf healthy feeling better barf uh oh sick again
我得到了这个输出:
Input line was:
barf barf barf healthy feeling better barf barf barf uh oh sick again
Output line is:
better sick again
Input line was:
barf barf healthy feeling better barf barf uh oh sick again
Output line is:
better sick again
Input line was:
barf healthy barf feeling better barf uh barf oh sick again
Output line is:
healthy feeling uh oh again
Input line was:
barf healthy feeling better barf uh oh sick again
Output line is:
healthy better uh sick again
我只是使用了一个简单的比较,而不是实际的正则表达式。我只是想说明算法。输出是否符合要求?