用c语言编写一个函数实现两个字符串的比较,即自己写一个strcmp函数,函数原型为“int strcmp(char* p1,char* p2);”设p1指向字符串s1,p2指向字符串s2,要求当s1==s2时,函数返回值为0;若s1≠s2,则返回二者中第一个不相同字符的ASCII码差值(如"BOY"与"BAD"的第二个字母不同,'O'与'A'之差为79-65=14)。 输入格式: 首先输入一个正整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据输入两个字符串s和字符串t。其中s、t的长度不超过10,且只包含英文字母。 输出格式: 对于每组测试,输出调用自己编写的strcmp函数的比较结果。
时间: 2023-11-27 22:54:52 浏览: 40
以下是使用 C 语言编写的 `strcmp` 函数的实现:
```c
#include <stdio.h>
int strcmp(char* p1, char* p2) {
while (*p1 != '\0' && *p1 == *p2) {
p1++;
p2++;
}
return *p1 - *p2;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
char s[11], t[11];
scanf("%s%s", s, t);
printf("%d\n", strcmp(s, t));
}
return 0;
}
```
首先,`strcmp` 函数通过循环遍历两个字符串,直到遇到不相等的字符或者其中一个字符串结束。在循环过程中,每次比较两个指针所指向的字符,如果相等则将指针向后移动,继续比较下一个字符。如果遇到不相等的字符,则函数返回这两个字符的 ASCII 码差值。
在主函数中,首先输入测试数据组数 `T`,然后依次输入每组测试数据,调用 `strcmp` 函数比较两个字符串,并输出比较结果。
相关问题
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
```
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;如果第一个字符串小于第二个字符串,则返回负整数;如果第一个字符串大于第二个字符串,则返回正整数。