文档创建日期:2010-02-19
01 // P174: 2.编程题 (13)不利用strcmp函数,自己编程实现两个任意字符串的比较。
02
03 // The beginning of C program: test06-13.c.
04
05 // Header files included.
06 #include <stdio.h>
07
08 // Macro definition.
09 #define MAX_SIZE 100
10
11 // No.1: Subroutine: int getstr ( char ch[], int size );
12 int getstr ( char ch[], int size )
13 {
14 int i=0;
15 if ( size >= MAX_SIZE )
16 {
17 printf ( "Input error, data will overflow!/n" );
18 return (0);
19 }
20 do
21 {
22 ch[i] = getchar();
23 i++;
24 } while ( ch[i-1] != '/n' );
25 ch[i-1] = '/0';
26 // 返回0表示调用该函数来获取字符串时获取失败,否则为获取成功
27 return (1);
28 }
29
30 // No.2: Subroutine: int strlength ( const char source[] );
31 int strlength ( const char source[] )
32 {
33 int length=0;
34 while ( source[length] != '/0' )
35 length ++;
36 return (length);
37 }
38
39 // No.3: Subroutine: int strcompare ( const char ch_1[], const char ch_2[] );
40 int strcompare ( const char ch_1[], const char ch_2[] )
41 {
42 // 返回的result值的正负说明两个字符串的大小关系,与系统的库函数定义相同
43 int result=0, len_1=0, len_2=0, i=0, min_size=0;
44 len_1 = strlength(ch_1);
45 len_2 = strlength(ch_2);
46 min_size = ( len_1 < len_2 ) ? len_1 : len_2;
47 for ( i=0; i<=min_size; i++ )
48 {
49 if ( (result=ch_1[i]-ch_2[i]) > 0 )
50 break;
51 else
52 if ( (result=ch_1[i]-ch_2[i]) < 0 )
53 break;
54 else
55 result = 0;
56 }
57 // 说明两个字符串中除去相同的部分后,较长的字符串较大,否则两个字符串完全相同
58 if ( (result==0) && (len_1 < len_2) )
59 result = -1;
60 else
61 if ( (result==0) && (len_1 > len_2) )
62 result = 1;
63 else
64 if ( (result==0) && (len_1==len_2) )
65 result = 0;
66
67 return (result);
68 }
69
70 // Main function's declaration.
71 int main ( void )
72 {
73 char ch_1[MAX_SIZE], ch_2[MAX_SIZE];
74 int i=0, size1=60, size2=60;
75
76 printf ( "Please input the first line of characters: " );
77 if ( getstr(ch_1, size1) == 0 )
78 return (1);
79 printf ( "Please input the second line of characters: " );
80 if ( getstr(ch_2, size2) == 0 )
81 return (2);
82
83 if ( strcompare(ch_1, ch_2) > 0 )
84 printf ( "The first string is larger than the second one./n" );
85 else
86 if ( strcompare(ch_1, ch_2) < 0 )
87 printf ( "The first string is smaller than the second one./n" );
88 else
89 printf ( "The first string is equal to the second one./n" );
90
91 return (0);
92 }
93
94 // The end of C program: test06-13.c.
95
此程序尚待改进!