...

/

String Handling Using the C Standard Library

String Handling Using the C Standard Library

Learn how the C standard library enables us to manage strings using functions for concatenating strings, finding their lengths, testing for equality, as well as allowing conversions between strings and numbers.

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.

Press + to interact
#include <stdio.h>
int main() {
// Concatenating two string constants and printing the resulting string
printf("Paul" " Gribble");
return 0;
}

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.

Press + to interact
#include <stdio.h>
#include <string.h>
int main(void) {
char s1[] = "Paul";
char s2[] = "Gribble";
char s3[256] = "";
printf("s3 = %s , strlen(s3) = %ld\n", s3, strlen(s3));
strcat(s3, s1);
printf("s3 = %s , strlen(s3) = %ld\n", s3, strlen(s3));
strcat(s3, " ");
printf("s3 = %s , strlen(s3) = %ld\n", s3, strlen(s3));
strcat(s3, s2);
printf("s3 = %s , strlen(s3) = %ld\n", s3, strlen(s3));
return 0;
}

Comparing

...