Lesson 10.3. The string.h library

The string.h library is a standard C library. It contains various functions for string manipulation. This page presents some of the most frequently used ones, but this presentation is not exhaustive.

#include <string.h>

Length of a string

The strlen() function that we have already used in this course returns the number of characters (up to the zero at the end of the string).

size_t strlen(const char *);

Copy a string

The strcpy() function (string copy) copies the source string to the destination string. Be careful, the destination string must be large enough to accommodate the copy. The characters are copied up to the null character.

char *strcpy(char *destination, const char *source);

String comparison

The strcmp() function (string compare) compares two strings. The function returns 0 if the strings are identical, a non-zero value otherwise.

int strcmp(const char *s1, const char *s2);

String concatenation

A string concatenation is the operation of joining strings end-to-end.

The function strcat() (string concatenate) adds the string source to the end of the string destination. As for the strcpy() function, it is necessary that the destination string must be large enough to accommodate the two strings end-to-end.

char * strcat ( char * destination, const char * source );


Exercise 1

Write a program that asks the user to enter his first name (50 characters maximum), then his last name (50 characters maximum). Then, the program creates and displays a string message that contains the text "Hello First Name Last Name.".

The program must create a string with the full name before displaying it. In other words, you have to use a function from the string.h library.

For example:

First name : Justin
Last name : Case
Hello Justin Case

Exercise 2

We provide the following strings:

#define   TEXT  "Text to copy."
char src[] = TEXT;
char dest[] = "String for the copy.";

Write the code that copies the string str into the string dest, then check that the copy is equal to TEXT. If the copy was successful, the program displays the program displays Copy OK, otherwise it displays Copy error.

Copy OK


The string.h library...

Check Bravo! string.h is usually installed by default with compilers. Try again...

The strcpy() function ...

char *strcpy(char *s1, const char *s2);
Check Bravo! strcpy(dest, src) means string copy. Try again...

The strcat() function ...

char *strcat(char *s1, const char *s2);
Check Bravo! The prototype of the function is char * strcat ( char * destination, const char * source ); Try again...

With the strcat() and strcpy() functions, the size of the destination string ...

Check Bravo! The destination string must be large enough before calling the function. Try again...

See also

Last update : 11/28/2022