Notes on character strings in C

Synopsis

To initilise a string of characters, use double quotation marks.

char myString[] = "Hello!";

This declaration is the equivalent of the statement

char myString[] = {'H', 'e', 'l', 'l', 'o', '!', '\0'};

\0 is the NULL character in C, and it is used to denote the termination of an array of chars.

To display a character string inside the printf function use the %s wildcard

printf("Value of myString is: %s \n", myString);

Why double quotation marks only?

In C (and in C++) single quotes identify a single character (char), while double quotes create a string literal. ‘a’ is a single a character literal (char), while “a” is a string literal containing an ‘a’ and a null terminator (effectively a 2 char array).

An example of string concatenation in C:

#include <stdio.h>

void concat(char result[],
            char string1[],
            char string2[])
{
    // Add string 1.
    char string1Char = string1[0];
    int i = 0;
    
    while (string1Char != '\0') {
        
        result[i] = string1[i];
        
        i++;
        string1Char = string1[i];
    }
    
    // Add string 2.
    char string2Char = string2[0];
    int u = 0;
    int j = i;
    
    while (string2Char != '\0') {
        
        result[j] = string2[u];
        
        u++;
        j++;
        string2Char = string2[u];
    }
    
    // Add NULL char.
    result[j] = '\0';
}

int main(int argc, const char * argv[])
{
    char firstName[] = "Jon";
    char lastName[] = "Matthews";
    char result[12];
    
    concat(result, firstName, lastName);
    
    printf("%s\n", result);
    
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *