c语言用一个函数实现两个字符串的比较
时间: 2023-04-25 12:05:11 浏览: 68
可以使用strcmp函数来比较两个字符串。该函数的原型为:
int strcmp(const char *s1, const char *s2);
其中,s1和s2分别为要比较的两个字符串。如果s1等于s2,返回值为0;如果s1小于s2,返回值为负数;如果s1大于s2,返回值为正数。
例如,比较字符串s1和s2:
int result = strcmp(s1, s2);
if (result == 0) {
printf("s1和s2相等\n");
} else if (result < 0) {
printf("s1小于s2\n");
} else {
printf("s1大于s2\n");
}
相关问题
c语言写一个函数实现两字符串比较
好的,这是 C 语言实现字符串比较的函数:
```c
#include <stdio.h>
#include <string.h>
int strcmp(const char *s1, const char *s2) {
int i = 0;
// 遍历两个字符串,直到出现不同字符或者到达字符串末尾
while (s1[i] == s2[i]) {
if (s1[i] == '\0')
return 0;
i++;
}
// 比较不同字符的 ASCII 码值,返回比较结果
if (s1[i] < s2[i])
return -1;
else
return 1;
}
int main() {
char str1[20] = "hello";
char str2[20] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("The two strings are the same.\n");
} else if (result < 0) {
printf("The first string is smaller than the second.\n");
} else {
printf("The first string is larger than the second.\n");
}
return 0;
}
```
这个函数通过比较两个字符串中每个字符的 ASCII 码值来判断它们的大小关系,并返回比较结果。如果两个字符串相同,则返回 0;如果第一个字符串小于第二个字符串,则返回负整数;如果第一个字符串大于第二个字符串,则返回正整数。
c语言写一个函数实现两个字符串的比较过程
可以使用strcmp()函数来实现两个字符串的比较过程。
strcmp()函数的原型如下:
```c
int strcmp(const char *str1, const char *str2);
```
其中,str1和str2分别表示需要比较的两个字符串。
如果两个字符串相等,strcmp()函数将返回0;如果str1小于str2,返回一个负数;如果str1大于str2,返回一个正数。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "hello";
char str2[20] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1和str2相等\n");
} else if (result < 0) {
printf("str1小于str2\n");
} else {
printf("str1大于str2\n");
}
return 0;
}
```
输出结果为:
```
str1小于str2
```