|
What is string variable? |
A string is a collection of characters. The characters may
include alphabets, digits and speacila characters. A variable that is used to
store a string is called string variable.
The last character of every string variable is a null
character. The null character is denoted by “\0”. This character marks the end
of string. Thus when data is entered into a string variable, null character at
the end of string will be added automatically. Thus if a string variable is declared
with 10 characters, it can store only 9 characters.
Suppose the size of string variable is 12. The value
“Pakistan” is assigned to it. The storage of this variable in memory is shown
below.
Declaring string
variable
Specifying the name of string variable and its length is
called declaring string variable. The data type of string variable is char
type. The maximum number of characters that a string variable is to store is
specified in square brackets in declaration statement.
The syntax to declare a string type variable is:
Char string [len];
Where
String Specifies
the name of string variable.
Len Specifies
the size or length of string variable. It is an unsigned integer value.
For example, to declare the string variables “name” and address of length 25 and 35 respectively, the
statement is written as:
Char
name[25], address [35]
Initializing string
variable
Like other variable, a string variable can also be
initialized with a string at the time of its declaration. For example, to
declare a string variable ‘str’ and to assign a string “Pakistan” into it, the
statement is written as:
Char str [14] = “Pakistan”
The string “Pakistan” will be assigned to string variable
“str” as show below:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
P
|
A
|
K
|
I
|
S
|
T
|
A
|
N
|
\0
|
|
|
|
|
|
A String variable can also be declared and initialized with
a string without specifying its length. For example, above statement can be
written as:
Char str[] = “Pakistan”;
In the above statement, the string variable str is declared
and Pakistan is assigned to it. The null character (\0) will be added at the
end of the string.
String input and
output
The gets() function and scanf() function can be used for
input data into a string variable. Mostly, the gets() function is used for this
purpose. Similarly, puts() function and
printf() function are used to display the data of string variable on the
screen. The format specifier “%s” with formatted input and output function is
used for input data into string and to display its data respectively.
For example, to display the contents of ‘str’ variable, the
statement is written as;
Printf (“% s’ , str);
No comments: