For string handling C provides a standard set of library functions. Though there exists many
such functions four of them will be discussed here.
The strcmp( ) Function
This function is used to check whether two strings are same or not. If both the strings are same it return a 0 or else it returns the numeric difference between the ASCII values of nonmatching characters e.q. the following program
# include"stdio.h"
main( )
{
char string1 [ ] = “orange”;
char string2 [ ] = “banana”;
printf(“%d\n”, strcmp(string1, string2));
printf(“%d\n”, strcmp(string2, “banana”);
printf(“%d”, strcmp(string1, “Orange”));
getch( );
}
output
13
0
32
In the first printf statement we use the strcmp( ) function with string1 and string2 as it argu- ments. As both are not equal (same) the function strcmp( ) returned 13, which is the numeric difference between “orange” and “banana” ie, between string2 and b.
In the second printf statement the arguments to strcmp() are string2 and “banana”. As string2
represents “banana”, it will obviously return a 0.
In the third printf statement strcmp( ) has its arguments “orange” and “Orange” because string1 represents “Orange”. Again a non-zero value is returned as “orange” and “Orange” are not equal.
strcpy( ) Function
The function copies one string to another for e.g. the following program
# include "stdio.h"
main( )
{
char source [ ] = “orange”; char target [20];
strcpy(target, source);
clrscr( );
printf(“source: %s\n”, source);
printf(“target:%s”, target);
getch( );
}
output will be
source : orange target : orange
strcat( )
This function concatenates the source string at the end of the target string for e.g, “Bombay” and “Nagpur” on concatenation would result in to a string “Bombay Nagpur”. Here is an ex- ample of strcat( ) at work.
main( )
{
char source [ ] = “Folks”;
char target [30] = “Hello”;
strcat(target, source);
printf(“\n source string = %s”, source);
printf(“\n target string = %s”, target);
}
And here is the output source string = folks target string = Hello folks
strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following program.
main( )
{
char arr[ ] = “Bamboozled”
int len1, len 2;
len1 = strlen(arr);
len2 = strlen(“Hunpty Dumpty”);
printf(“\n string = %s length = %d”, arr, len1);
printf(“\n string = %s length = %d”, “Humpty Dumpty”, len2);
}
The output would be
string = Bamboozled length=10
string = Humpty Dumpty length = 13
while calculating the length of the string it does not count ‘\0’.
such functions four of them will be discussed here.
The strcmp( ) Function
This function is used to check whether two strings are same or not. If both the strings are same it return a 0 or else it returns the numeric difference between the ASCII values of nonmatching characters e.q. the following program
# include"stdio.h"