此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
文本就是字符数组
- C 没有单独的字符串类型。字符串就是一个
char数组。 char word[] = "hi";实际上存了'h'、'i',以及末尾一个隐藏的'\0'。- 你可以用下标一个字符一个字符地读,和任何数组完全一样。
看不见的结束符 '\0'
- 每个 C 字符串都以一个特殊的空字符结束符结尾,写作
'\0'(一个等于0的字节)。 - 它标记文本在哪里停止。单词
"hi"占 三 个字节:'h'、'i'、'\0'。 - 函数遇到
'\0'就知道字符串结束了 —— 字符串并不存储自己的长度。
遍历字符串
- 要访问每个字符,让下标在
s[i] != '\0'时循环。 - 当
s[i]变成'\0'时,你就到了末尾 —— 停下来。 - 这就是手动统计字符、查找或复制字符串的方法。
English
#include <stdio.h>
int main(void) {
char word[] = "hello";
int len = 0;
while (word[len] != '\0') { // stop at the terminator
len++;
}
printf("%d\n", len); // 5
return 0;
}
<string.h> 工具箱
<string.h>提供了现成的助手:strlen(s)(长度)、strcpy(dst, src)(复制)、strcmp(a, b)(比较)、strcat(dst, src)(连接)。strcmp(a, b)在两个字符串相等时返回0—— 在测试里很好用。- 它们都依赖
'\0'结束符来知道每个字符串在哪里结束。
常见错误
- 字符串要多留一个字节给
\0:5 个字母的词要char[6]。 - 比较字符串用
strcmp,不是==。
现在轮到你
- 要就地修改字符串,调用者必须传进来一个可写的
char数组,而不是固定的文本。 - 让你的循环在
'\0'处停下。不要自己写main—— 检查器会提供。
探索
Strings are arrays of characters
Index each character from 0; the slice shows a range of chars.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete int count_char(const char *s, char c) so it returns how many times c appears in the string s. Loop until you reach the end of the string. Do 不 write a main.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete int my_strlen(const char *s) so it returns the length of s without calling strlen. Walk the array until you reach the end. Do 不 write a main.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete void reverse_str(char *s) so it reverses the characters of s in place. Find the length, then swap from both ends toward the middle. Do 不 write a main.
点击“运行”查看此处输出。