08 May 2012

Use of Strings in 'C'

A string is defined in 'C' as an array (list) of characters.

char str[10];   defines a string variable of 10 characters.

When data is placed in a string variable, a null character is placed at the end of the data. It is possible to look for this null when processing the string, so that processing
does not go past the end of the valid data.

A string variable should always be declared with enough characters to hold the longest possible piece of data, plus one for the null. For instance, if you want a variable which stores names, you must first determine the length of the longest name which might occur, and declare the variable with one extra character.

It is possible to look at the characters in a string individually, by using an index. (a number which indicates the position of the character within the string) The first character is at position 0, the second at position 1, etc.
char str[10] = "My Name";
printf("%c", str[0]);  //will print M
printf("%c", str[4]);  //will print a
The index can be a variable, so:
char str[10] = "Your Name";
for(int x=8; x >= 0; x--)
    printf("%c", str[x]);
will print the string in reverse order.

To look for the null character in a string variable, use code like:

if(str[x] == '\0') // '\0' represents a null

No comments:

Post a Comment