2. 编写一个程序,其中用户自定义函数strcompare函数实现两个字符串s1,s2的比较,函数原型声明为:int strcompare( char *str1 , char *str2 ) ; 分别有如下要求: (1)调用函数时实参用数组名,函数形参用指针变量。 (2)调用函数时实参和函数形参都用指针变量。 (3)调用函数时实参用指针变量,函数形参用数组名。
时间: 2024-02-21 12:01:10 浏览: 303
设计字符串比较的函数
方案1:
```c
#include <stdio.h>
#include <string.h>
int strcompare(char *str1, char *str2);
int main() {
char s1[100], s2[100];
printf("请输入两个字符串:\n");
scanf("%s%s", s1, s2);
int result = strcompare(s1, s2);
if(result > 0) {
printf("字符串%s大于字符串%s\n", s1, s2);
} else if(result < 0) {
printf("字符串%s小于字符串%s\n", s1, s2);
} else {
printf("字符串%s等于字符串%s\n", s1, s2);
}
return 0;
}
int strcompare(char *str1, char *str2) {
return strcmp(str1, str2);
}
```
方案2:
```c
#include <stdio.h>
#include <string.h>
int strcompare(char *str1, char *str2);
int main() {
char s1[100], s2[100];
printf("请输入两个字符串:\n");
scanf("%s%s", s1, s2);
int result = strcompare(s1, s2);
if(result > 0) {
printf("字符串%s大于字符串%s\n", s1, s2);
} else if(result < 0) {
printf("字符串%s小于字符串%s\n", s1, s2);
} else {
printf("字符串%s等于字符串%s\n", s1, s2);
}
return 0;
}
int strcompare(char *str1, char *str2) {
int i = 0;
while(str1[i] && str2[i] && str1[i] == str2[i]) {
i++;
}
return str1[i] - str2[i];
}
```
方案3:
```c
#include <stdio.h>
#include <string.h>
int strcompare(char str1[], char str2[]);
int main() {
char s1[100], s2[100];
printf("请输入两个字符串:\n");
scanf("%s%s", s1, s2);
int result = strcompare(s1, s2);
if(result > 0) {
printf("字符串%s大于字符串%s\n", s1, s2);
} else if(result < 0) {
printf("字符串%s小于字符串%s\n", s1, s2);
} else {
printf("字符串%s等于字符串%s\n", s1, s2);
}
return 0;
}
int strcompare(char str1[], char str2[]) {
int i = 0;
while(str1[i] && str2[i] && str1[i] == str2[i]) {
i++;
}
return str1[i] - str2[i];
}
```
阅读全文