字符串内容与标识
Coddy 面向 R 开发者的 C 课程的第 15 课,共 48 课。
R 的 == 会逐个元素比较字符串内容,并返回一个逻辑向量。因此,只要字符相同,用不同方式构建的两个字符串就相等;R 不会向你显示字符串存储的位置。C 中对两个 char 指针使用 == 比较的是地址,而不是文本。strcmp 会逐字节比较以空字符结尾的字符串,并返回负数、零或正数;不要假设返回值一定是 -1 或 1,也不要期待它像 R 对字符串使用 < 时那样按照区域设置进行排序。
R
a <- "cat"
b <- paste0("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。
挑战
简单输入是一行 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;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 C中的所有课
自己练习: C 在线编译器