生成代码(已知任意字符串S1和S2,在串的顺序存储结构上实现S1和S2的比较运算,并返回比较结果)
时间: 2024-02-12 14:04:56 浏览: 85
以下是在串的顺序存储结构上实现S1和S2的比较运算的代码:
```
#include <stdio.h>
#include <string.h>
// 定义串的最大长度
#define MAX_LEN 100
// 定义比较结果的枚举类型
enum CompareResult {
LESS_THAN = -1,
EQUAL = 0,
GREATER_THAN = 1
};
// 比较字符串S1和S2的大小关系
int compare(char* S1, char* S2) {
int len1 = strlen(S1);
int len2 = strlen(S2);
int len = len1 < len2 ? len1 : len2;
for (int i = 0; i < len; i++) {
if (S1[i] < S2[i]) {
return LESS_THAN;
} else if (S1[i] > S2[i]) {
return GREATER_THAN;
}
}
if (len1 == len2) {
return EQUAL;
} else if (len1 < len2) {
return LESS_THAN;
} else {
return GREATER_THAN;
}
}
int main() {
// 读入S1和S2
char S1[MAX_LEN + 1], S2[MAX_LEN + 1];
printf("请输入S1:");
scanf("%s", S1);
printf("请输入S2:");
scanf("%s", S2);
// 比较S1和S2
int result = compare(S1, S2);
// 输出比较结果
if (result == LESS_THAN) {
printf("S1 < S2\n");
} else if (result == EQUAL) {
printf("S1 = S2\n");
} else {
printf("S1 > S2\n");
}
return 0;
}
```
该程序首先读入两个字符串S1和S2,然后调用compare函数比较它们的大小关系,最后根据比较结果输出相应的字符串。在compare函数中,我们先比较S1和S2的前缀,如果有不同的字符,则直接返回它们的大小关系;如果前缀相同,则比较它们的长度。如果S1和S2长度相等,则它们相等;否则,长度较长的串大。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)