Strings
Work with text as arrays of characters and use the string.h functions.
C has no separate string type. A string is an array of char that ends with a special null character '\0'. That final zero tells functions such as printf where the text stops.
int main(void) {
char word[] = "code"; /* stored as 'c' 'o' 'd' 'e' '\0' */
printf("%s\n", word);
printf("%c %c\n", word[0], word[3]);
printf("array size: %zu\n", sizeof(word));
return 0;
}
code c e array size: 5
The array holds 5 characters, not 4, because of the hidden '\0'.
The string.h library
int main(void) {
char first[20] = "Data";
char second[] = "Science";
printf("length: %zu\n", strlen(first));
strcat(first, " "); /* append */
strcat(first, second);
printf("joined: %s\n", first);
char copy[20];
strcpy(copy, second); /* copy */
printf("copy: %s\n", copy);
printf("compare: %d\n", strcmp("apple", "apple") == 0);
return 0;
}
length: 4 joined: Data Science copy: Science compare: 1
Walking through a string
Because a string ends with '\0', you can loop until you reach it.
int main(void) {
char text[] = "Hello World 2026";
int vowels = 0, digits = 0;
for (int i = 0; text[i] != '\0'; i++) {
char ch = tolower(text[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else if (isdigit(ch)) {
digits++;
}
text[i] = toupper(text[i]);
}
printf("%s\n", text);
printf("vowels: %d, digits: %d\n", vowels, digits);
return 0;
}
HELLO WORLD 2026 vowels: 3, digits: 4
Building strings with snprintf
snprintf works like printf but writes into an array, and never writes more than the size you give it.
int main(void) {
char label[32];
snprintf(label, sizeof(label), "Roll no. %03d (%s)", 7, "B");
printf("%s\n", label);
return 0;
}
Roll no. 007 (B)
GATE-style practice questions
What does the following program print?
int main(void) {
char s[] = "GATE2026";
printf("%zu %zu\n", strlen(s), sizeof(s));
return 0;
}
Show answer and explanation
Answer: Bstrlen counts the characters before the terminating '\0': 8. The array also stores that '\0', so sizeof(s) is 9.
What does the following program print?
int main(void) {
char s[] = "programming";
char *p = s;
while (*p) p++;
printf("%d\n", (int)(p - s));
return 0;
}
Show answer and explanation
Answer: 11The loop moves p forward until it reaches the '\0' at the end, so p − s is the length of "programming", which is 11.
What does the following program print?
int main(void) {
char s[] = "abcdef";
printf("%s\n", s + s[1] - s[0] + 2);
return 0;
}
Show answer and explanation
Answer: Bs[1] − s[0] is 'b' − 'a' = 1, so the expression is s + 1 + 2 = s + 3, which points at "def".