14.P112课后习题4-13:设串采用静态数组存储结构,编写函数Compare(S,T)实现两个串的比较。要求比较结果有大于、等于和小于三种情况。
头文件:SString.h
#include <stdio.h>
#define MaxSize 100
typedef struct
{
char str[MaxSize];
int length;
}String;
void Initiate(String* S)
{
S->length = 0;
}
int Insert(String* S, int pos, String T)
{
int i;
if (pos<0 || pos>S->length)
{
printf("参数pos出错! ");
return 0;
}
else if (S->length + T.length > MaxSize)
{
printf("数组空间不足无法插入!");
return 0;
}
else
{
for (i = S->length - 1; i >= pos; i--)
S->str[i + T.length] = S->str[i];
for (i = 0; i < T.length; i++)
S->str[pos + i] = T.str[i];
S->length = S->length + T.length;
return 1;
}
}
int Delete(String* S, int pos, int len)
{
int i;
if (S->length <= 0)
{
printf("数组中未存放字符无元素可删!\n");
return 0;
}
else if (pos < 0 || len<0 || pos + len>S->length)
{
printf("参数pos和len不合法");
return 0;
}
else
{
for (i = pos + len; i <= S->length - 1; i++)
S->str[i - len] = S->str[i];
S->length = S->length - len;
return 1;
}
}
int SubString(String S, int pos, int len, String* T)
{
int i;
if (pos < 0 || len<0 || pos + len>S.length)
{
printf("参数pos和len出错");
return 0;
}
else
{
for (i = 0; i < len; i++)
T->str[i] = S.str[pos + i];
T->length = len;
return 1;
}
}
源文件:main.c
#include "SString.h"
int Compare(String S, String T)
{
int i = 0, j = 0, tag;
while (i < S.length && j < T.length)
{
if (S.str[i] == T.str[j])
{
i++;
j++;
}
else if (S.str[i] > T.str[j])
{
tag = 1;
return tag;
}
else
{
tag = -1;
return tag;
}
}
if (S.length == T.length)
tag = 0;
else if (S.length > T.length)
tag = 1;
else if (S.length < T.length)
tag = -1;
return tag;
}
int main()
{
String string1 = { "ABCD", 4 },string2 = { "ABCDE", 5 };
printf("比较结果为: %d\n", Compare(string1, string2));
return 0;
}