Strings
| English | Chinese | Pinyin |
|---|---|---|
| string | 字符串 | zì fú chuàn |
| ordered sequence | 有序序列 | yǒu xù xù liè |
| characters | 字符 | zì fú |
| Concatenation | 拼接 | pīn jiē |
| Length | 长度 | cháng dù |
| substring | 子串 | zi chuàn |
| user input | 用户输入 | yòng hù shū rù |
Text is a string
- Text in a program is stored as a string 字符串.
- A string is an ordered sequence 有序序列 of characters 字符.
- "Hello" is a string of five characters.
- Order matters, so "abc" and "cba" are different strings.
A string is:
Order matters, so "abc" ≠ "cba".
Concatenating "sun" and "flower" gives:
Concatenation joins them in order into one string.
What is the length of the string "cat"?
It has 3 characters: c, a, t.
String operations
- Concatenation 拼接 joins strings into one: "sun" + "flower" gives "sunflower".
- Length 长度 is how many characters a string holds — the length of "cat" is 3.
- A substring 子串 is a part of a string: from "computer" you can take "put".
- You can also read one character by its position.
Index and slice a string
Every character has a position (index from 0). A slice takes characters from the start index up to — but not including — the end index.
If counting starts at 0, the character at position 0 of "cat" is:
Position 0 is the first character, "c".
A part of a string, such as "put" from "computer", is called a ______.
A substring is a slice of the original string.
Positions and indexing
- Positions are counted from a starting number.
- Many languages start at $0$, so in "cat" position $0$ is "c" and position $2$ is "t".
- A substring takes characters from a start index up to — but not including — an end index.
- Always check where a language starts counting.
Concatenating "Hi, " + "Ana" + "!" produces:
The three strings join in order to greet the user.
Processing user input
- These operations process user input 用户输入 — text a user types, like a name.
- A program might read a name, find its length, and greet the user by joining strings.
Greeting. Read the name "Ana" into name; its length is 3. Build the greeting by concatenation: "Hi, " + name + "!" gives "Hi, Ana!" — the output shown to the user.
A string is an ordered sequence of characters, so order matters. Key operations are concatenation (join), length (count), and substring (a part). Positions are usually indexed from 0, and a slice runs up to but not including the end index. Strings let a program process user input.