We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

C String Library

The C standard library provides a comprehensive set of functions to manipulate strings in the <string.h> header file. Here are some of the most commonly used functions:

  • strcpy: Copies a string to another.
    char src[] = "Hello";
    char dest[6];
    strcpy(dest, src);
    // dest now contains "Hello"
    
  • strncpy: Copies a specified number of characters from one string to another.
    char src[] = "Hello";
    char dest[6];
    strncpy(dest, src, 3);
    // dest now contains "Hel"
    dest[3] = '\0';
    // ensure null termination
    
  • strcat: Concatenates (appends) one string to another.
    char dest[12] = "Hello";
    char src[] = " World";
    strcat(dest, src);
    // dest now contains "Hello World"
    
  • strncat: Concatenates a specified number of characters from one string to another.
    char dest[12] = "Hello";
    char src[] = " World";
    strncat(dest, src, 3);
    // dest now contains "Hello Wo"
    
  • strlen: Returns the length of a string (excluding the null terminator).
    char str[] = "Hello";
    size_t len = strlen(str);
    // len is 5
    
  • strcmp: Compares two strings lexicographically.
    char str1[] = "Hello";
    char str2[] = "World";
    int result = strcmp(str1, str2);
    // result is negative since "Hello" < "World"
    
  • strchr: Finds the first occurrence of a character in a string.
    char str[] = "Hello";
    char *pos = strchr(str, 'l');
    // pos points to the first 'l' in "Hello"
    
  • strstr: Finds the first occurrence of a substring in a string.
    char str[] = "Hello World";
    char *pos = strstr(str, "World");
    // pos points to "World" in "Hello World"
    

Assignment

Complete the smart_append function. It appends a src string to the buffer field inside the dest TextBuffer struct.

The TextBuffer struct tracks both the buffer and its current length. It's called a "smart" append because the destination buffer is a fixed 64 bytes, and it:

  • Checks for available space before appending.
  • Appends as much as possible if there's not enough space.
  • Always ensures the buffer remains null-terminated.
  • Returns a status indicating whether the full append was possible.

Here are the steps:

  1. In C, NULL represents a null pointer, which does not point to a value.