String
is a simply an array of characters terminated by a null (or null character).
Or
A
string is a null-terminated character array. (A null is zero.)
Or
A
string contains the characters that make up the string followed by a null.
When
declaring a character array that will hold a string, you need to declare it to
be one character longer than the largest string that it will hold. For example,
to declare an array str that can hold a 10-character string, we would write
char
str[11];
Specifying
11 for the size makes room for the null at the end of the string.
When
we use a quoted string constant in our program, we are also creating a
null-terminated string. A string constant is a list of characters enclosed in
double quotes.
Example:
"hello there, this is a string"
Character
arrays that hold strings allow a shorthand initialization that takes the form:
char str[size] = "this is string";
This
is the same as writing
char str[size] = { `t`, `h`, `i`, `s`, ` `, `i`, `s`, ` `, `s`, `t`, `r`, `i`, `n`, `g`, `\0` };
Because
strings end with a null. We can also put 0 in place of `\0`.
This
is why str is 15 characters long even though "this is string" is only
14.
When
we use the string constant, the compiler automatically supplies the null terminator.
We
do not need to add the null to the end of string constants manually— the
compiler does this automatically.
[Note:
C++ also defines a string class, called string, which provides an
object-oriented approach to string handling, but it is not supported by C.]
C
supports a wide range of functions in <string.h> header that manipulate
strings.
The
most common are listed here:
Name
Function
strcpy(s1,
s2) Copies s2 into s1
strcat(s1,
s2) Concatenates s2 onto the
end of s1
strlen(s1)
Returns the length of
s1
strcmp(s1,
s2) Returns 0 if s1 and s2 are
the same; less than 0 if s1<s2; greater than 0 if s1>s2
strchr(s1,
ch) Returns a pointer to the
first occurrence of ch in s1
strstr(s1,
s2) Returns a pointer to
the first occurrence of s2 in s1
Arrays
of Strings:
To
create an array of strings, we use a two-dimensional character array. The size
of the left dimension determines the number of strings, and the size of the
right dimension specifies the maximum length of each string. The following declares
an array of 30 strings, each with a maximum length of 79 characters:
char
str_array[30][80];
It
is easy to access an individual string: we simply specify only the left index.
For example, the following statement calls gets( ) with the third string in
str_array.
gets(str_array[2]);
The
preceding statement is functionally equivalent to
gets(&str_array[2][0]);
Examples: