Strings: char arrays and the null terminator
Text is an array of chars
- C has no separate string type. A string is just an array of
char. char word[] = "hi";actually stores'h','i', and a hidden'\0'at the end.- You can read one character at a time with an index, exactly like any array.
The invisible terminator '\0'
- Every C string ends with a special null terminator, written
'\0'(a byte equal to0). - It marks where the text stops. The word
"hi"takes three bytes:'h','i','\0'. - Functions know a string has ended when they reach
'\0'— there is no stored length.
Walking a string
- To visit each character, loop an index while
s[i] != '\0'. - When
s[i]becomes'\0', you have reached the end — stop. - This is how you count characters, search, or copy a string by hand.
#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;
}
The <string.h> toolbox
<string.h>has ready-made helpers:strlen(s)(length),strcpy(dst, src)(copy),strcmp(a, b)(compare),strcat(dst, src)(join).strcmp(a, b)returns0when the two strings are equal — handy in tests.- These all rely on the
'\0'terminator to know where each string ends.
Common mistakes
- A string needs one extra byte for
\0: a 5-letter word needschar[6]. - Compare strings with
strcmp, not==.
Now you try
- To change a string in place, the caller must pass a writable
chararray, not a fixed text. - Stop your loops at
'\0'. Do not write amain— the checker provides one.
Strings are arrays of characters
Index each character from 0; the slice shows a range of chars. · ใช้ดัชนีแต่ละอักขระตั้งแต่ 0; การตัดช่วงแสดงช่วงของอักขระ
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 not write a main. · เติมเต็ม int count_char(const char *s, char c) ให้ส่งกลับจำนวนครั้งที่ c ปรากฏใน string s. ลูปจนกว่าคุณจะถึงท้าย string. ห้าม เขียน main
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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 not write a main. · เติมเต็ม int my_strlen(const char *s) ให้ส่งกลับความยาวของ s โดยไม่ เรียก strlen. เดินผ่าน array จนกว่าคุณจะถึงท้าย string. ห้าม เขียน main
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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 not write a main. · เติม void reverse_str(char *s) เพื่อกลับหัวกลับท้ายของ s แบบใน-place. หาความยาว, แล้วสลับจากปลายทั้งสองเข้าหาตรงกลาง. ห้าม เขียน main
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่