Previous Index Next

STRING: It is an array of type char.

Syntax for declaration

char <array/string name> [max. number of characters to be stored +1];

The number of elements that can be stored in a string is always n-1, if the size of the array specified is n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always terminated with the NULL character.

Example:
char str[80];
In the above example, str can be used to store a string with 79 characters.

Initializing a string

A string can be initialized to a constant value when it is declared.

char str[ ] = "Good";
    Or
char str[]={'G','o','o','d','\0'};

Here. 'G' will be stored in str[0], 'o' in str[1] and so on.

Note: When the value is assigned to the complete string at once, the computer automatically inserts the NULL character at the end of the string. But, if it is done character by character, then we have to insert it at the end of the string.

Reading strings with/without embedded blanks

To read a string without blanks scanf can be used
scanf("%s", str);
To read a string with blanks gets() can be used.

gets(str);

Printing strings

printf() and puts() can be used to print a string.
printf("%s", str);
   Or
puts(str);

String Library Functions

The string-handling library (<string.h>) provides many useful functions for manipulating string data

strlen(s) Determines the length of string s.
strcmp(s1,s2) compares its first string argument to its second string argument, character by character. It returns 0 if the strings are equal, returns a negative value if the first string is less than the second and returns a positive value if the first string is greater than the second.
strcpy(s1,s2) Copies string s2 into array s1. The value of s1 is returned.
strcat() Appends string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.
strstr() Locates the first occurrence in string s1 of string s2. If the string is found, a pointer to the string in s1 is returned. Otherwise, a NULL pointer is returned.

 

 

Previous Index Next

privacy policy