C 语言实现 strcmp 函数376


strcmp() 函数是 C 标准库中比较字符串的标准函数。它返回一个整数,指示其第一个参数与第二个参数的相对位置。若第一个字符串小于第二个字符串,则返回 -1;若相等,则返回 0;若第一个字符串大于第二个字符串,则返回 1。

strcmp() 函数的原型int strcmp(const char *str1, const char *str2);
其中:
* `str1`:要比较的第一个字符串。
* `str2`:要比较的第二个字符串。

strcmp() 函数的工作原理strcmp() 函数通过逐个比较两个字符串的字符来工作。它从字符串的第一个字符开始比较,如果字符相同,它将继续比较下一个字符。此过程一直持续到:
* 两个字符不同。
* 两个字符串之一达到末尾('\0' 字符)。
如果两个字符串长度相等并且所有字符都相同,则 strcmp() 函数返回 0。

strcmp() 函数的实现以下是 strcmp() 函数的一个简单实现:

int strcmp(const char *str1, const char *str2) {
while (*str1 == *str2) {
if (*str1 == '\0') {
return 0;
}
str1++;
str2++;
}
return *str1 - *str2;
}

strcmp() 函数的示例以下是一些 strcmp() 函数的示例:
```c
#include
#include
int main() {
const char *str1 = "Hello";
const char *str2 = "World";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2");
} else if (result == 0) {
printf("str1 is equal to str2");
} else {
printf("str1 is greater than str2");
}
return 0;
}
```
输出:
```
str1 is less than str2
```

2024-10-22


上一篇:C 语言分段函数的详细用法和示例

下一篇:将色彩斑斓的文字输出到 C 终端