Monday, December 05, 2011

Coding lessons: C and strings (lesson 10)

In the last C lessons I talked about Arrays, I sort of gave some poor examples of how you may want to use an array for storing co-ordinate data, (for a map or a graph?) but really I just needed to introduce the concept.

In programming a string is a series of characters, each and every word I type is a string, this sentence is a string.

Strings are groups of characters all placed side by side in an array.

Boxes

The simplest way to describe an array is to look at a single input as a box, our Char variable allows only a single character to be put into the variable, it's like a single box that's 8 bits wide (so it can store the 8 bit char.)

Arrays

An array is like a load of boxes all placed next to each other.

The word "example" is a string, it's an array of characters, that's 7 characters in length

e x a m p l e

so we have seven 8 bit wide boxes (one for each letter) placed side by side.

basically, a string is an array of characters,
BUT what separates a string from an array of charecters is that the last "data pocket" in the array that makes up a string is a special NUL character. (this is just a regular char with value 0)


We can create strings in two ways.
Either declare an array, then enter in the data, and enter in the NUL character ourselves, or we can declare and fill the string when declaring it.

#include <stdio .h>
int main()
{
char hello[6];
hello[0] = 'H';
hello[1] = 'e';
hello[2] = 'l';
hello[3] = 'l';
hello[4] = 'o';
hello[5] = '\0';

printf("%s", hello);
return(0);
}


but that is a very difficult way of working with strings, in order to do more complex stuff with strings we will need to include the library string.h

in this next example we can see that we can have the compiler automatically see that we're creating a string, and not only create an array of the correct size of what we're trying to put in there, but also add the NUL character into the end of the array also.

#include <stdio .h>
int main()
{
char hello[6];
char world[] ="world";
hello[0] = 'H';
hello[1] = 'e';
hello[2] = 'l';
hello[3] = 'l';
hello[4] = 'o';
hello[5] = '\0';

printf("%s %s", hello, world);
return(0);

}

Notice in both these examples that when poking characters into the array they are contained in a single quote.
single quotes for characters, double quotes for strings.

hello[0] = "H";
Doesn't work because as H is contained inside double quotes it's data type is a string. you can't put a string of data into a single char space of data. trying to do this will result in a program that throws errors whilst compiling.

No comments: