测试回文,感觉写的好复杂
main() 用来测试的,不用去管。程序代码:
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int palindrome( char *string ); int main( void ) { char s1[10000]; int i; int ch; FILE *fp; if( NULL == ( fp = fopen( "word.txt","r" ) ) ) { fprintf( stderr, "Error\n" ); exit( EXIT_FAILURE ); } for( i = 0; 10000 - 1 > i && EOF != ( ch = fgetc( fp ) ); i++ ) s1[ i ] = ch; s1[ i ] = '\0'; while( 'y' == ( ch = getchar() ) ) { while( '\n' != getchar() ) ; if( 1 == ( i = palindrome( s1 ) ) ) printf( "Yes\n" ); else if( -1 == i ) printf( "Error\n" ); else printf( "No\n" ); } fclose( fp ); getchar(); return 0; } void reverse( char *src ); enum { Error = -1, No = 0, Yes = 1}; int palindrome( char *string ) { char *s1, *s2; char temp[ strlen( string ) ];//VS或VC这一行可能通不过编译。 int CharAmount; int Limit; int i; if( 0 == strlen( string ) ) return Error; for( CharAmount = 0, i = 0; '\0' != *string; string++ ) if( isalpha( *string ) ) { temp[ i++ ] = tolower( *string ); CharAmount++; } temp[ i ] ='\0'; Limit = CharAmount / 2; s1 = ( char * )malloc( ( Limit + 1 ) * sizeof( char ) ); s2 = ( char * )malloc( ( Limit + 1 ) * sizeof( char ) ); if( NULL == s1 || NULL == s2 ) return Error; strncpy( s1, temp, Limit ); *( s1 + Limit ) = '\0'; if( CharAmount % 2) strncpy( s2, temp + Limit + 1, Limit ); else strncpy( s2, temp + Limit, Limit ); *( s2 + Limit ) = '\0'; reverse( s2 ); i = strcmp( s1, s2 ); free( s1 ); free( s2 ); if( 0 == i ) return Yes; else return No; } void reverse( char *src ) { char *s1, *s2; char temp; s1 = src; s2 = src; while( '\0' != *s2 ) s2++; s2--; for( ; s1 < s2; s1++, s2-- ) { temp = *s1; *s1 = *s2; *s2 = temp; } }
[此贴子已经被作者于2017-3-13 15:41编辑过]