Introduction To Strings in C
Posted by
Ravi Kumar at Monday, September 19, 2011
Share this post:
|
The way a group of integers can be stored in an integer
array, similarly a group of characters can be stored in a
character array . Character array are often called strings.
A string constant is a one-dimensional array of characters
terminated by a null('\0').The ASCII value of ('\0') is 0.
Each character in the array occupies one byte of memory
and the last character is always'\0'.
The following example illustrates how a string is stored
and accessed
main()
{
static char name[]="Nagpur";
int i=0;
while (name[i]!='\0')
{
printf("%c",name[i]);
i++;
}
}
A string can also be initialized as
static char[]="Nagpur";
Here '\0' is not necessary . C inserts it automatically.
The terminating null('\0') is important,because it is the only
way the functions that work with a string can know where the
string ends.
Declaring and Initializing string variables:
A string variable is any valid c variable name and is
always declared as an array .The general form of declaration of
a string variable is:
char string_name [size];
The size determines the number of characters in the
string_name.The size should be equal to the maximum number of
characters in the string plus one.'C' permits a character
array to be initialized in either of the following two forms
static char city[9] = "Newyork";
static char city[9] = {'N','E','W','Y','O','R','K','\0'};