Menu
CoddyTech

字符串内容与身份

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

Ruby 的 == 会比较字符串内容,而 equal? 会检查两个名称是否指向同一个 String 对象。C 中 char 指针上的 == 与 equal? 类似:它比较的是地址,而不是文本。strcmp 会按字典顺序比较以 null 结尾的字符串,并返回负值、零或正值;与 Ruby 的 <=> 不同,不要假设返回值的绝对值一定是 1。

Ruby

a = "cat"
b = "cat"
puts [a == b, a.equal?(b)].inspect

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";const char *p=a,*q=b;printf("%d %d\n",strcmp(p,q)==0,p==q);
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自我测试

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

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

自己练习: C 在线编译器