C语言:写一个函数,实现两个字符串的比较。即自己写一个stringCompared函数,函数原型为:int stringCompared(char * p1,char * p2);,设p1指向字符串s1,p2指向字符串s2。要求当s1==s2时,返回值为0,当s1!=s2时,返回他们两者第一个不同的字符的ASCII码差值,如果s1>s2,则输出一个正值,如果s1<s2,则输出一个负值。
时间: 2023-12-14 07:35:58 浏览: 15
下面是实现stringCompared函数的代码:
```c
int stringCompared(char *p1, char *p2) {
int i = 0;
while (*(p1 + i) == *(p2 + i)) {
if (*(p1 + i) == '\0') {
return 0;
}
i++;
}
return *(p1 + i) - *(p2 + i);
}
```
该函数通过循环比较两个字符串中的字符,当遇到不同的字符时,返回它们的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
```
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;如果第一个字符串小于第二个字符串,则返回负整数;如果第一个字符串大于第二个字符串,则返回正整数。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](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)
![](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)