A C string is a char array terminated by \0. <string.h> provides length, copy, concatenation, and comparison functions; the caller must ensure destination buffers are large enough.
#include <stdio.h>
#include <string.h>
int main(void) {
char first[16] = "Leaf";
char second[] = "let";
strcat(first, second);
printf("%s has %zu characters\n", first, strlen(first));
return 0;
}strlen: count to the terminator
strlen scans from the first character to \0. The returned length excludes the terminator.
strlen terminator scanner
Move the scan pointer one cell at a time. Count ordinary characters, then stop at \0 without counting it.
strcpy: overwrite the destination
strcpy(destination, source) copies every character and the final \0. The destination array must fit the entire result.
strcpy character-by-character copy
The destination starts empty. Each step writes source[i] into destination[i], including the final \0.
destination[0] = source[0];Copy character “C”.
strcat: append at the terminator
strcat(destination, source) finds the destination’s \0, appends source there, and writes a new terminator.
strcat concatenation buffer
First scan destination to its \0, then copy source from that position and finish by writing a new \0.
destination[0] != '\0'Keep scanning right so the original content is not overwritten.
strcmp: lexicographic comparison
strcmp(a, b) returns a negative value, zero, or a positive value. The sign represents ordering; the value is not guaranteed to be exactly -1 or 1.
strcmp first-difference locator
Scan both strings together. Continue while characters match; the first mismatch determines the sign of the result.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Safely concatenate a name
Read a first and last name and safely build “first last” in a fixed-capacity buffer, reporting an error if it does not fit.
- Read first and last and remove trailing newlines.
- Check strlen(first) + strlen(last) + 2 before concatenating.
- Copy and concatenate only when the complete result fits.
Sort three words lexicographically
Read three words, compare their contents with strcmp, and print them in lexicographic order.
- Store the words in a two-dimensional character array.
- Compare neighboring strings and swap complete contents when out of order.
- Print all three words after sorting.
Merge two text lines
Safely read two text lines, merge them into a sufficiently large character array, and insert one space between them.
- Read both lines with fgets and remove trailing newlines.
- Calculate capacity for both lines, the space, and the terminator.
- Copy the first line, space, and second line only when they fit.