As a group of an integer is called as integer array. Similarly, a group of character is called as character array. A character array is known as String.
For example:
1 |
char name[]={'w','e','b','E','n','c','y','c','l','o','p','\0'} |
- Each character occupies one byte of memory.
- And the last character is always \0.
- ‘\0’ is called a null character.
- ASCII value of ‘\0’ is zero.
- %s is a format specifier use to print a string.
The following figure shows the way a character array is stored in memory.
The elements of the character array are stored in contiguous memory locations. The terminating null \0 is important.
The above example can also be initialized as,
1 |
char name[] = "webEncyclop"; |
In this declaration \0 is not necessary. C compiler automatically inserts a null character.
Example:
1 2 3 4 5 6 7 8 9 10 |
int main( ) { char name[] = "WebEnclyclop" ; int i = 0 ; while ( i <= 12 ) { printf ( "%c", name[i] ) ; i++ ; } } |
Output:
1 |
WebEnclyclop |
Program:
1 2 3 4 5 6 7 8 |
#include<stdio.h> int main( ) { char str1[10] = "Mumbai"; char str2[10] = {"M','u','m','b','a','i'}; printf("string is: %s\n", str1); printf("character array is: %s\n", str2); } |
Output:
1 2 |
string is: Mumbai character array is: Mumbai |
Points to remember:
-
1char a[5]="hello"; //error
Because given length is not sufficient for given string.
Actual length of string is 6 (hello(5) + ‘\0′(1) =6). Therefore above initialization is not valid. Hence correct initialization is:1char a[6]="hello"; - Name of the array itself is a constant pointer.
So it cannot be incremented nor decremented.12char a[6] = "hello";a++; //error
Standard Library String Functions:
Every C compiler has many sets of useful string handling functions. There are many important string functions defined in “string.h” library. The following list contain commonly used string functions:
- strlen
- strrev
- strlwr
- strupr
- strcat
- strncat
- strcpy
- strncpy
- strcmp
- strncmp
- strcmpi
- stricmp
- strnicmp
- strdup
- strchr
- strrchr
- strstr
- strset
- strnset
From the above list of functions strlen(), strcpy(), strcat(), strcmp() are the most commonly used functions.
Let us study these functions one by one.