Menu
CoddyTech

字符串的内容与标识

Coddy 面向 Python 开发者的 C 课程的第 15 课,共 48 课。

Python 中的 == 会比较字符串内容。C 中用于指针的 == 比较的是地址,而不是文本。strcmp 会按字典序比较以空字符结尾的字符串,并返回负值、零或正值;不要假设返回值的绝对值一定是 -1 或 1。

Python

print("cat"=="cat")

C17

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
char a[]="cat",b[]="cat";printf("%d\n",strcmp(a,b)==0);
return 0;
}

移植规则

在 C 中比较字符串内容时,请使用 strcmp。

challenge icon

挑战

简单

输入是一行 ASCII 文本。如果内容恰好是 yes,则返回 1,否则返回 0。匹配区分大小写,且不会去除空格。

编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,因为该文件会直接调用它。不要添加另一个 main。除非任务明确检查范围,否则所有数值任务数据都足够小,不会发生溢出。只打印指定的输出;如有显示,驱动程序会负责解析输入和输出。

亲手试试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){char text[128]="";if(fgets(text,sizeof text,stdin))text[strcspn(text,"\n")]=0;printf("%d\n",is_yes(text));return 0;}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Python 开发者的 C中的所有课

自己练习: C 在线编译器