Strings

Strings

A string is a word, formed by combining letters.

H, e, l, l, o ➡️ Hello


Some languages (Python) have a datatype for strings, however not C.

In C, we define a string as an array of characters.

char var[] = "Hello";

In C, we define a string as an array of characters.

char var[] = "Hello";

  • The [] indicates that var is an array of type char
  • The word is wrapped in quotes - not apostrophes
Letterchar c = 'H';
Stringchar w[] = "Hello";

Printing Strings

To print a string, we can use the printf function.

char str[] = "Hello!";
printf("%s", str);
The "%s" tells the function to display str as a string

The Null Character ‘\0’

Every byte of data is stored in a different memory address. They however are kept in the same region.

int main(void) {
    char string1[] = "Foo";
    char string2[] = "Bar";
    char string3[] = "Buzz";
}

Our memory should look something like this:
‘F’, ‘o’, ‘o’, ‘B’, ‘a’, ‘r’, ‘B’, ‘u’, ‘z’, ‘z’

However, we do not have a way of figuring out which memory is for what variable!

To solve this, we append a special symbol which indicates the end of the string.
This symbol is the NULL character, represented by \0

NULL character - \0

Our memory looks like this:
‘F’, ‘o’, ‘o’, ‘\0’, ‘B’, ‘a’, ‘r’, ‘\0’, …

The Null Character ‘\0’

char w[] = "Hi";

When using a string enclosed in apostrophes, the NULL character is automatically added.

char w[] = {'H','i','\0'}

If we decide to define our string with characters, we need to make sure to put the NULL character in!

The Null Character ‘\0’

char w[] = "Hello\0World!";

A string is identified from the first character to the first NULL character.

If we wrote printf("%s", w); - we would see “Hello”, and would not see the word “World”

char w[] = {'H','i','\0'}

If we decide to define our string with characters, we need to make sure to put the NULL character in!

Review

Is the expression "H" valid?

Is the expression "Hello" valid?

Is the expression 'Hello' valid?

Is the expression '' valid?

Is the expression "" valid?

What is the equivalent definition of the following
char word[] = "Computer";?


char word[] = { ??? };

Inspecting Strings

We can extract a single character from a string
by using its positional index. We count indices from $0$.


char word[] = "Computer";


word[0] is ‘C’
word[1] is ‘o’

word[7] is ‘r’

word[8] is ‘\0’

Mutating Strings

Like changing variables, we can change characters in strings with the assignment operator '='

#include <stdio.h>

int main(void) {
    char word[] = "Fire";
    printf("Current word is %s.\n", word);

    word[2] = 'l';
    word[3] = 'l';
    printf("New word is %s.\n", word);

    return 0;
}
$> ./program
Current word is Fire.
New word is Fill.
Home