Lesson 14 of 31

Strings

Strings

In C, strings are arrays of char terminated by a null byte ('\0'). There is no dedicated string type.

String Literals

const char *greeting = "Hello";

This creates a string {'H', 'e', 'l', 'l', 'o', '\0'} in memory and stores its address in greeting.

Subspace messages: character arrays transmitted across the quadrant, always null-terminated so you know where the message ends.

Character Arrays

You can also store strings in character arrays:

char name[10] = "Alice";

This copies the string into the name array. You can modify it (unlike string literals).

String Functions (string.h)

FunctionDescription
strlen(s)Returns the length (excluding null terminator)
strcmp(s1, s2)Compares two strings (0 if equal)
strcpy(dest, src)Copies src into dest

Printing Strings

printf("%s\n", greeting);    // Hello
puts(greeting);               // Hello (adds newline automatically)

Iterating Characters

const char *s = "Hello";
for (int i = 0; s[i] != '\0'; i++) {
    printf("%c", s[i]);
}
printf("\n");

Your Task

Write a function int count_char(const char *s, char c) that counts how many times character c appears in string s. Call it from main to count the letter 'l' in "hello world" and print the result.

TCC compiler loading...
Loading...
Click "Run" to execute your code.