Menu
CoddyTech

字符串内容与标识

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

Lua 字符串是不可变的值,== 会按内容比较它们:用 .. 构建的字符串与字节相同的字面量相等。C 中的 == 比较指针地址,而不是文本。strcmp 会按字典顺序比较以空字符结尾的字符串,并返回负值、零或正值;不要假设返回值一定是 -1 或 1。

Lua

local a = "cat"
local b = "c" .. "at"
print(a == b)

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自我测试

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

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

自己练习: C 在线编译器