STRINGS
(Character Arrays)
A string is a sequence of characters. Any sequence or set
of characters defined within double quotation symbols is a constant string.
Definition: A string can be defined as a group of characters,
terminate with a NULL character (\0). Since there is no separate datatype to
declare strings, we declare a string as an array of characters using the
datatype char.
Declaration:
char stringname[size];
A string
variable is any valid C variable and is always declared as an array. The size determines
the number of characters in the string.
Ex:
char city[10];
char name[20];
When the compiler assigns
a character string to a character array. It automatically supplies a null
character (‘\0’) at the end of the string. Therefore the size should be equal
to the maximum number of character in the string plus one.
Initialization of strings:
A
string can be initialized in different ways:
Eg:
char name[5]={‘R’,’A’,’J’,’U’,’\0’};
char name[5]=”RAJU”;
In the first way we are
initializing the string by element by element .In this case we must explicitly
specify the null character.
In the second example we are
initialize string in double quotations so,system automatically assigns the null
character.
A string is always terminated by
a NULL character ‘\0’, which represents the end of the string.
Representation:
R
|
A
|
J
|
U
|
\0
|
Ex2: char city [10] = {‘h’,’y’,’d’,’e’,’r’,’a’,’b’,’a’,’d’,
’\0’};
char city[10] = “hyderabad ”;
The reason that city had to be 10 elements long is that the string “hyderabad ” contains 9
characters and one element space is provided for the null terminator. So the size of the string must be length of
the string plus one.
C also permits us to initialize a
character array without specifying the number of elements. In such cases, the
size of the array will be determined automatically based on the number of
elements initialized. For example
char
string [] = {‘g’,’o’,’o’,’d’,’\0’}
defines the array string as a five element
array.
No comments:
Post a Comment