Text

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Text

Character

Each character is assigned with a number (code). The character/number mapping is defined by the ASCII table. That table only contains 127 characters and the only alphabet it contains is the english one. To represent other characters (Such as 'é'), we need to use other methods, but this is a subject for an other time.

For example, the character A inside the ASCII table has the character code 65. You may consult the ASCII table, here.

Because the ASCII table only contains 128 characters (The biggest character code is 127), we use variables of type char to represent a single character.

Note that a character must be written inside apostrophes.

Here we define a variable holding the character 'A':

char character = 'A';

Note that the variable 'character' actually holds the value 65, as this is the ASCII character code of the letter A.

Strings

Text is represented as a sequence (array) of characters. We call a sequence of characters a string.

In C, strings are null-terminated. All that means is that all strings are ended with the value zero (To mark its end). The ASCII character with the code 0 is called the 'null character'.

Here we define an array storing the string "Sky":

char str[] = "Sky";

Note that the size of 'str' actually is 4 because of the null character at the end.

We can print strings simply put giving them to the function 'printf':

main.c

1
2
3
4
5
6
7
8
9
10
#include <stdio.h> int main() { char str[] = "Sky\n"; printf(str); return 0; }

We can also use '%s':

printf("%s", str);

Note that 'printf' prints the characters inside the array it received as argument, as long as it does not reach a character with the value 0.

Comparing two strings

We can not directly compare strings with ==. We must compare each character individually.

The function 'strcmp' from the C Standard Library returns 0 only if the two strings it received as arguments are equal.

Note that we must include the file <string.h> to use it.

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string.h> int main() { char str[] = "Blue"; if(strcmp(str, "Red") == 0) printf("The strings are equal.\n"); else printf("The strings are different.\n"); return 0; }