Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – Characters and Strings

It’s time to delve into one of the enormously useful topics of programming: working with text.

Characters and Strings

In the past few programs, we’ve used the printf() function quite a bit. This magical little function generates strings and prints them to the terminal. But what exactly is a “string?”

First, we have to understand what a character is. A character is a collection of bits which the computer can interpret and translate into a symbol. Every single letter, punctuation mark, and whitespace character in this blog post is a character.

In C, the char data type stores one 8-bit value which is translated into an ASCII character.

One character is rarely enough for us. If you had to read this entire post one character at a time, you would stop reading and send me nasty emails. This is where strings come in.

A string is a collection of characters which are interpreted at the same time. For example, if we use the function:

printf(“This is a string, right here!”)

all the text inside the quotation marks is interpreted as one string.

Those C++ and Java programmers out there are probably already aware that C does not have a specific “string” class. That doesn’t mean that we can’t create strings easily, however. We simply have to use a pointer (which we will discuss in detail later – much later). The same string can be stored in a variable as:

char * this_string = “This is a string, right here!”

When we want to print a string using printf(), we use the %s tag to represent where the string should go. For example, if I wanted to just print this_string, I’d write:

printf(“%sn”, this_string)

We’ll go into more detail on the nuances of printf() later.

char_string.c

You know the drill by now. Create a file named char_string.c with the following contents:


#include <stdio.h>

int main(int argc, char *argv[])
{
//Double quotes tell the compiler we're using a string
char * help = "This is some help text\n";
char * hello = "Hello, world!\n";
//Single quotes tell the compiler we're using a character
char letter = 'a';

int i = 0;
printf("%sSee how that worked?\n", help);
//The tag %c represents a character
printf("The letter A: %c\n", letter);
for(i = 0; i < 5; i++)
{
//The tag %d represents an integer
printf("Pass %d: %s", i, hello);
}
return 0;
}

I assume that you know how to use gcc to compile such a simple program by now. If not, your assignment is to look at the previous examples and figure it out.