String Manipulation In C Language With Exaples
Strings:
In C a string is defined as a character array which is terminated by a special character, the null character ' ', as there is no string type as such in C.
Thus the string or character array must always be defined to be one character longer than is needed in order to cater for the ' '.
For Example :- string to hold 5 characters
char s[6];
A string constant is simply a list of characters within double quotes e.g. “Hello” with the ' ' character being automatically appended at the end by the compiler.
A string may be initialised as simply as follows
char s[6] = “Hello”;
'H' |
'e' |
'l' |
'l' |
'o' |
'\ 0' |
as opposed to
char s[6] = { 'H', 'e', 'l', 'l', 'o', ' ' };
Again the size specification may be omitted allowing the compiler to determine the size required.
Manipulating Strings:
We can print out the contents of a string using printf() as we have seen already or by using puts().
CODE/PROGRAM/EXAMPLE
printf( "%s", s ) ;
puts( s ) ;
Strings can be read in using scanf()
Syntax
scanf( "%s", s ) ;
where we do not require the familiar & as the name of an array without any index or square braces is also the address of the array.
A string can also be read in using gets()
There is also a wide range of string manipulation functions included in the C Standard Library which are prototyped in which you should familiarise yourself with.
For Example :-
CODE/PROGRAM/EXAMPLE
char s1[20] = “String1”, s2[20] = “String2” ;
int i ;
strcpy( s1, s2 ) ; /* copies s2 into s1. */
i = strcmp( s1,s2 ) ; /* compares s1 and s2. It returns zero if
s1 same as s2,-1 if s1 < s2, and +1 if s1 > s2 */
i = strlen( s1 ) ; /* returns the length of s1 */
strcat ( s1, s2 ) ; /* Concatenates s2 onto end of s1 */