CodeBlanks Logo Icon CodeBlanks

string.h

  • C course
  • Intermediate
  • Lesson 83/116
  • 4 min

Learn string functions in string.h.

string.h

The <string.h> header provides functions that work on C strings (char arrays): copy (strcpy), concatenate (strcat), length (strlen) and compare (strcmp).

In C a string is a null-terminated char array. strcpy(dst, src) copies src into dst. strcat(dst, src) appends src to the end of dst. strlen(s) returns the character count excluding null. strcmp(a, b) returns 0 if equal, negative if a is smaller, positive if larger. None of these check memory bounds; the destination array must be large enough. Modern C also has bounded variants like strncpy and strncat.

The strcpy and strcat example

To build a string from scratch, start with strcpy and add pieces with strcat. The destination array must be large enough.

Example: char buf[64]; strcpy(buf, "42"); strcat(buf, " + 58");. The first strcpy writes 42 into buf (3 bytes including null). strcat appends + 58; now buf holds 42 + 58. strlen(buf) returns 7 (excluding null). Output: 7 42 + 58. The 64-byte buf is plenty. If the destination were small, strcat would overflow and cause undefined behavior. Always check the destination size.

Practice Build a string

In main declare char buf[64];. Start with strcpy(buf, "42");. Append with strcat(buf, " + 58");. Print length and string with printf("%zu %s\n", strlen(buf), buf);.

Starter code

main.c
#include <stdio.h>
#include <string.h>

// main: char buf[64]; copy "42" with strcpy
// append " + 58" with strcat
// get length with strlen, print with printf

int main(void) {
    // write here
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[64];
    strcpy(buf, "42");
    strcat(buf, " + 58");
    printf("%zu %s\n", strlen(buf), buf);
    return 0;
}

Expected output

7 42 + 58

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 string functions

Term Meaning
strcpy copy
strcat append
strlen get length
strcmp compare

2 The strcat call

Question
strcat(buf, ____);
Answer
strcat(buf, " + 58");

Explanation: strcat appends the second argument to the first.

3 What does strlen("42 + 58") return?

  • 7 Correct answer
  • 0
  • 6
  • 8

Explanation: strlen returns the character count excluding null: 7.

All lessons in Intermediate