C 语言中比较字符串的方法有:使用 strcmp() 函数比较两个字符串的全部内容。使用 strncmp() 函数比较两个字符串的前 n 个字符。使用循环和字符比较手工比较字符串。

C 语言中比较字符串的方法
在 C 语言中,字符串表示为字符数组。要比较两个字符串,可以使用以下方法:
1. 使用 strcmp() 函数
strcmp() 函数比较两个字符串,返回一个整数:
立即学习“C语言免费学习笔记(深入)”;
示例:
<code class="c">#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
// 打印结果
printf("strcmp() result: %d\n", result);
return 0;
}</code>该代码将打印 -5,因为 "Hello" 小于 "World"。
2. 使用 strncmp() 函数
strncmp() 函数比较两个字符串的前 n 个字符,返回一个整数:
示例:
<code class="c">#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "HelloWorld";
int result = strncmp(str1, str2, 5);
// 打印结果
printf("strncmp() result: %d\n", result);
return 0;
}</code>该代码将打印 0,因为 "Hello" 和 "HelloWorld" 的前 5 个字符相等。
3. 使用循环和字符比较
也可以使用循环和字符比较手工比较字符串:
<code class="c">#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int i = 0;
int result = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] < str2[i]) {
result = -1;
break;
} else if (str1[i] > str2[i]) {
result = 1;
break;
}
i++;
}
if (str1[i] == '\0' && str2[i] != '\0') {
result = -1;
} else if (str1[i] != '\0' && str2[i] == '\0') {
result = 1;
}
// 打印结果
printf("手工比较结果: %d\n", result);
return 0;
}</code>该代码将打印 -1,因为 "Hello" 小于 "World"。
以上就是c语言怎么对比字符串的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号