Strings in C
C Programming Lesson 9 2:28 English narration · English + 中文 subtitles burned in
Chapters
Transcript
C has no string type at all.
C 根本没有字符串类型。
What it has is an array of char, and everything about strings in this language follows from that.
它有的是 char 数组, 而这门语言里关于字符串的一切,都由此而来。
Write the word hi and you get an h and an i — and a third byte you never typed, holding zero.
写下 "hi",你得到一个 h、一个 i——还有一个你从没敲过的第三个字节,值是 0。
It is called the null terminator, and it is what marks the end of the text.
它叫空字符结尾符,正是它标出文本到哪里为止。
So the word hi takes three bytes, and forgetting that is the source of most C string bugs.
所以 "hi" 占三个字节,而忘掉这一点,正是大多数 C 字符串 bug 的来源。
Because nothing records how long a string is, every function that needs the length has to walk it: one box at a time, from the start, until it meets the zero byte.
因为没有任何地方记录字符串有多长,每个需要长度的函数都得自己走一遍: 从头开始,一个格子一个格子,直到遇见那个 0 字节。
That is the whole shape of my_strlen, and it is what the real strlen does too.
my_strlen 的结构就是这样,真正的 strlen 做的也是同一件事。
Worth knowing for a practical reason: there is no stored length, so calling strlen inside a loop condition re-walks the whole string on every single pass.
这一点有实际意义:长度没有被存下来, 所以把 strlen 写在循环条件里,会让它每一轮都把整个字符串重走一遍。
You do not have to write all of these yourself.
这些你不必全都自己写。
Include string dot h and you get ready-made helpers: strlen for the length, strcpy to copy one into another, strcat to join two together.
include <string.h>,就有现成的工具: strlen 求长度,strcpy 把一个复制到另一个里,strcat 把两个接起来。
And strcmp to compare — but read its answer carefully.
还有 strcmp 用来比较——但要仔细看它的返回值。
It returns zero when they are equal, not one.
两个字符串相等时它返回 0,不是 1。
So an if on strcmp is true when the strings DIFFER, which is exactly backwards from what it looks like.
所以直接把 strcmp 放进 if,条件为真反而表示两个字符串不同, 正好和它看起来的意思相反。
Now the lesson's third task: reverse a string in place.
现在做课程里的第三道题:原地反转一个字符串。
Find the length first, then use two indexes — one at each end.
先求出长度,然后用两个索引——一头一个。
Swap and step inward, and stop when they meet in the middle.
交换,然后各自往里走一步,在中间相遇时停下。
The detail that decides whether it works: j starts at n minus one, the last real character, not at n.
决定它能不能成立的细节是:j 从 n 减 1 开始,也就是最后一个真正的字符,而不是 n。
Start it at n and you swap the terminator into the middle, and the string ends there.
从 n 开始的话,你会把结尾符换到中间,字符串就在那里断掉了。
Four things to take with you.
带走四点。
One: a string is just an array of char.
第一:字符串就是一个 char 数组。
Two: a hidden zero byte marks the end, so text takes one byte more than it looks.
第二:一个隐藏的 0 字节标记结尾,所以文本占的字节数比看上去多一个。
Three: to walk a string, loop while s at i is not the zero byte.
第三:要遍历字符串,就在 s 不是 0 字节时继续循环。
Four: strcmp returns zero when the two are equal.
第四:strcmp 在两者相等时返回 0。
Now do the three tasks; the first counts one character.
现在去做那三道题;第一题是数某个字符出现了多少次。