Skip to content

Chapter 10 of 21

Strings and String Handling

Handle null-terminated text with standard functions and bounds awareness.

30 minutes 10 quick checksBy Subha Prasad
Lesson 10 of 21Course navigation

Lesson content

Read, practise, then check your understanding

C has no built-in string type. A string is an array of char ending with a null byte ('\0'). The capacity of an array and its current string length are different values.

char editable[16] = "hello";   // capacity 16, length 5
const char *literal = "world"; // do not modify a string literal

Length, copy, and comparison

<string.h> declares strlen, strcmp, memcpy, memmove, memset, and related functions. strlen scans to a null terminator and excludes it.

if (strcmp(command, "start") == 0) {
    start_service();
}

Do not compare text with ==; that compares pointer values.

Bounded construction

Before copying, prove that destination capacity is at least source length + 1.

int copy_text(char *destination, size_t capacity, const char *source) {
    if (!destination || !source) return 0;
    size_t length = strlen(source);
    if (length >= capacity) return 0;
    memcpy(destination, source, length + 1);
    return 1;
}

strncpy is not a universal safe replacement: it may omit termination and pads unused capacity. Prefer an interface whose truncation or failure policy is explicit. snprintf is useful for formatted text and returns the length that would have been written.

Reading input

Never use gets. Use fgets, check its result, and remove a trailing newline if present.

char line[128];
if (fgets(line, sizeof line, stdin) != NULL) {
    line[strcspn(line, "\n")] = '\0';
}

If input exceeds capacity, fgets reads only part. Robust code detects a missing newline and drains or grows the buffer according to policy.

Bytes, Unicode, and parsing

A C string is a byte string. UTF-8 can represent one character with multiple bytes, so strlen counts bytes, not user-perceived characters. For numbers, prefer strtol or strtod over atoi; they expose errors and the unparsed suffix. Always carry capacity with writable buffers and treat external text as untrusted.

Knowledge check

Answer every question correctly to complete this chapter.

Which byte marks the end of a C string?
Why is strcpy risky when the destination size is unknown?
Does strlen include the terminating null byte?
How should two C strings be compared for content?
Which function safely reads a bounded line including spaces?
What does char editable[16] = "hello" provide?
Why is strncpy not a universal safe replacement for strcpy?
What does strlen count in UTF-8 text?
Which function is preferable to atoi for validated integer parsing?
What must writable string APIs track in addition to current length?

0 of 10 checks passed

Your progress is saved on this device.

Strings and String Handling | C Lesson | Subha Prasad