Strings – C

String is an one dimensional array (vector) of characters which is ended by a null character ‘/0’. This means that in order to store a string “Hello” it is necessary to have a char array of 5 + 1 elements (“Hello” + ‘\0’) .

character array in memory

This post covers only string manipulations with statically declared char arrays.

Declaring strings

C language supports multiple ways of declaring strings andassigning values.

  1. Declare and initialize char array
  2. Declare char array, assign values later (e.g. sprintf, strcpy)
  3. Declare char pointer, allocate memory and assign value later (not covered in this post)

When declaring a character array be sure to have enough elements to store your string and a null terminator. This is essential to avoid common errors such as going out of array bounds when printing the string.

Another thing to keep in mind is that it is a good practice to initialize string with either the string value or all 0’s. This is to make sure that string is null terminated or when a value is copied to the string array, if the string is shorter than the elements of array – 1 then that string is also null terminated.

Examples of declaring strings:

#include <stdio.h>

int main(void) {
    // Declaring one dimensional char arrays (strings)
    // Note that for the first 2 preprocessor will give
    // enough memory to fit the string into char array (with '\0')
    char *str1 = "Hello";
    char str2[] = "CodingMeta";
    char str3[9] = "Strings!";
    char str4[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    // Print strings
    puts(str1);
    puts(str2);
    puts(str3);
    puts(str4);

    // Declaring Array of strings
    char *strings1[] = {
        "Hello",
        "CodingMeta"
    };
    char strings2[2][16] = {
        "Hello",
        "CodingMeta"
    };
    char strings3[][16] = {
        "Hello",
        "CodingMeta"
    };
    // Print strings
    puts(strings1[0]);
    puts(strings1[1]);
    puts(strings2[0]);
    puts(strings2[1]);
    puts(strings3[0]);
    puts(strings3[1]);

    return 0;
}
Hello
CodingMeta
Strings!
Hello
Hello
CodingMeta
Hello
CodingMeta
Hello
CodingMeta

string.h

C language has standard header string.h which defines multiple functions for string manipulations. This makes parsing strings much easier, improving the programmers’ development speed. List of functions available in string.h can be found in standard libraries post [ 2 ].

Examples of most commonly used functions in string library, for full list see [ 3 ]:

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

int main(void) {

    char str[] = "Quick brown fox jumped over the lazy dog.";
    char hello[] = "Hello!";
    char buffer[64] = {0};
    char *ptr = NULL;

    // String length with strlen, does not include 0 terminator
    printf("Length of '%s' is %lu characters\n", str, strlen(str));

    // Copy contents of str to buffer
    strcpy(buffer, str);
    puts(buffer); // Quick brown fox jumped over the lazy dog.

    // Clear buffer
    memset(buffer, 0, sizeof(buffer));

    // Copy the word Quick into buffer (n (5) characters)
    strncpy(buffer, str, 5);
    puts(buffer); // Quick

    // Concatenate strings - append to the string
    strcat(buffer, hello);
    puts(buffer); // QuickHello!

    // Compare 2 strings, 0 if same
    if (strcmp(hello, "Hello!") == 0) {
        puts("Strings are equal");
    } else {
        puts("Strings are different");
    }

    // Find the beginning of substring
    ptr = strstr(str, "fox");
    puts(ptr); // fox jumped over the lazy dog.
    ptr = NULL;
    
    // Split string into tokens, tokenize with space ' '
    ptr = strtok(str, " ");
    while (ptr != NULL) {
        // Prints each word on a separate line (space separated)
        puts(ptr);
        ptr = strtok(NULL, " ");
    }

    return 0;
}

Outputs:

Length of 'Quick brown fox jumped over the lazy dog.' is 41 characters
Quick brown fox jumped over the lazy dog.
Quick
QuickHello!
Strings are equal
fox jumped over the lazy dog.
Quick
brown
fox
jumped
over
the
lazy
dog.

NB! When manipulating strings, make sure that the destination string ALWAYS has enough memory to store the result string after modification. Don’t forget about the null terminator!

stdio.h

This header provides some useful functions for strings. Most noteworthy are puts and sprintf. Example usage of those:

#include <stdio.h>

int main(void) {
    char buffer[64] = {0};

    puts("Example of puts & sprintf");
    // Write formatted data to char array
    sprintf(buffer, "Formatted: %d %f %s", 7, 3.14, "Test");
    printf("String: '%s'\n", buffer);

    return 0;
}
Example of puts & sprintf
String: 'Formatted: 7 3.140000 Test'

Common mistakes

Using deprecated functions

One example of this is gets which scans string until it reaches newline or EOF. This means that using this function it is very likely to get a buffer overflow – going outside the bounds of the array. Therefore, it’s recommended not to use gets.

#include <stdio.h>

int main(void) {
    // Enough for Hello
    char str[6] = {0};
    puts("Enter a string:");
    gets(str);
    printf("Your string: '%s'\n", str);

    return 0;
}

This could output:

Enter a string:
Long string, will it crash or give garbage?
Your string: 'Long string, will it crash or give garbage?'
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)

Scanf string

Both examples have the solution and the commented out mistake.
Using scanf for strings but it stops at space:

// Solution
#include <stdio.h>

int main(void) {
    char buffer[32] = {0};

    puts("Enter a string:");
    // scanf("%s", buffer); <- does not work
    // Read everything except newline
    scanf("%[^\n]s", buffer);
    printf("String: '%s'\n", buffer);

    return 0;
}

Buffer overflow

#include <stdio.h>

int main(void) {
    char buffer[6] = {0};

    puts("Enter a string:");
    // scanf("%s", buffer); <- can cause buffer overflow (Stack smashing)
    // Read max 5 characters
    scanf("%5s", buffer);
    printf("String: '%s'\n", buffer);

    return 0;
}
Enter a string:
CodingMeta
String: 'Codin'

Resources

  1. Arrays [ Link ]
  2. Standard libraries [ Link ]
  3. string.h header [ Link ]

5 thoughts on “Strings – C

Comments are closed.