C语言请编程实现两个字符串的比较(不能使用库函数strcmp)
时间: 2024-01-07 15:04:59 浏览: 38
以下是C语言实现两个字符串比较的代码,该代码不能使用库函数strcmp:
```c
#include <stdio.h>
int CompareStr(char *str1, char *str2);
int main() {
char s1[20], s2[20];
gets(s1);
gets(s2);
if (CompareStr(s1, s2) > 0)
printf("%s比%s大\n", s1, s2);
else if (CompareStr(s1, s2) < 0)
printf("%s比%s小\n", s1, s2);
else
printf("%s与%s相等\n", s1, s2);
return 0;
}
int CompareStr(char *str1, char *str2) {
do {
if (*str1 > *str2)
return 1;
else if (*str1 < *str2)
return -1;
} while ((*str1++) && (*str2++));
return 0;
}
```
相关问题
请用C语言实现两个字符串的比较(不能使用库函数strcmp)
以下是用C语言实现两个字符串比较的代码,该代码不能使用库函数strcmp:
```c
#include <stdio.h>
int Compare(char str1[], char str2[]) {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return str1[i] < str2[i] ? -1 : 1;
}
i++;
}
if (str1[i] == '\0' && str2[i] == '\0') {
return 0;
} else {
return str1[i] == '\0' ? -1 : 1;
}
}
int main() {
char str1[80], str2[80];
printf("请输入字符串1:\n");
gets(str1);
printf("请输入字符串2:\n");
gets(str2);
if (Compare(str1, str2) == -1) {
printf("字符串1大于字符串2");
} else if (Compare(str1, str2) == 0) {
printf("字符串1等于字符串2");
} else {
printf("字符串1小于字符串2");
}
return 0;
}
```
用c语言编程,将两个字符串连接后升序排列
下面是一段C语言代码,实现了将两个字符串连接后升序排列的功能。其中使用了字符串库函数`strcmp`和`strcpy`。
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], temp[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
strcat(str1, str2); // 将两个字符串连接
int n = strlen(str1);
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(&str1[i], &str1[j]) > 0) { // 如果前面的字符串大于后面的字符串
strcpy(temp, &str1[i]); // 交换两个字符串
strcpy(&str1[i], &str1[j]);
strcpy(&str1[j], temp);
}
}
}
printf("The sorted string is: %s", str1);
return 0;
}
```
上述代码首先通过`scanf`函数获取两个字符串,并使用`strcat`函数将它们连接成一个字符串。接着使用双重循环遍历字符串中的所有子串,如果前面的子串大于后面的子串,那么就交换它们。最后输出排序后的字符串。