String Handling Using the C Standard Library
Explore how to handle strings in C using the string.h and stdlib.h libraries. Learn to concatenate, compare, find length, and convert strings to and from numeric types. Understand safe techniques for dynamic string allocation and perform deep comparisons with functions like strcmp. This lesson provides a solid foundation for string manipulation in C programming.
The C standard library (which we can load into our program by including the directive #include <string.h> at the top of our program), contains many useful routines for manipulating these null-terminated strings.
It’s a good idea to consult a reference source for a long list of all the functions that exist for manipulating null-terminated strings in C. There are functions for copying strings, concatenating strings, getting the length of strings, comparing strings, etc.
Concatenating and finding length
If we place two string constants together side by side, the C compiler will concatenate the constants. This doesn’t apply to strings that are stored as arrays of characters and for them we explicitly need to use the strcat function.
We can use the strcat function to concatenate two strings by appending the second string to the first one. We show this below, by passing the string s3 as the first argument in each call to strcat.
We can use the strlen function to find the length of a string in terms of characters that appear before the (first) null character.
Comparing two strings
Importantly, we cannot simply use the ...