String
There is no separate data type for string in C , they are
treated as array of characters. A character array is a string if it ends with a
null character (‘\0’). This null character is an escape sequence with
ASCII value 0 and is different from the
ASCII character ‘0’.
String are generally
used to store and manipulate data in text form like word or sentence.
String Constant
A string constant is a sequence of character enclosed in
double quotes and is also called a literal . ”double quote are not a part of
the string.e.g: “TAJ” “deep”.
String Liberary
Function:
There are several library functions used to manipulate
strings and the prototype for these functions are in header file string.h most commonly used string function like:
strlen(), strcpy(),strcmp(),strcat().
1.
Strlen()
|
Declaration: size_x strlen(char const *string);
This function returns the length of the string i.e the
number of character in the string excluding the terminating null character.
Program to understand strlen():
#include<stdio.h>
#include<string.h>
Int main(void)
{
Char str[50];
Printf(“enter
the string:”);
Gets(str);
Printf(“Length
of string:%d\n”,strlen(str));
Return 0;
}
|
2.
Strcpy
|
Declaration: char * strcpy(char *s1 , const char *s2);
This function is used for copying one string to another
string.
Program to understand strcpy():
#include<stdio.h>
#include<string.h>
Int main(void)
{
Char
str[50],str1[50];
Printf(“enter
the string:”);
Gets(str);
Strcpy(str1,str);
Printf(“first
string:%s\n second string:%s\n”,str,str1);
Return 0;
}
|
3.
Strcmp()
|
Declaration: int strcmp(char* s1,char *s2);
This function is used for lexicographic comparison of
two strings. If the two string match,strcmp() returns a vlue 0 otherwise it
returns a non-zero. It compares the string character by character and the
comparison stops when either the end of string is reached or the
corresponding characters in the two strings are not same.
Strcmp(s1,s2) return a value:
<0 when s1
<s2
=0 s1==s2
>0 s1>s2
/* program to understand the work of strcmp()
function*/
#include<stdio.h>
#include<string.h>
Main(void)
{
Char
str1[90],str2[90];
Printf(“enter two strings :”);
Gets(str1);
Gets(str2);
If((strcmp(str1,str2))==0)
Printf(“strings
are same\n”);
Else
Printf(“strings
are not same\n”);
Return 0;
}
Output: Enter two strings: Deepak
Kumar
Strings are not same.
|
4.
Strcat
|
Declaration : char* strcat(char*str1,const char*str2)
This function is used to append a copy of a string at the end of other string.e.g
if first string is “Cprogram” and second string is “stores “ then the output
will come as Cprogramstores
/* Program to understand strcat() function*/
#include<stdio.h>
#include<string.h>
int main(void)
{
char
str1[20],str2[20];
printf(“enter
two string:”);
gets(str1);
gets(str2);
strcat(str1,str2);
printf(“%s\n”,str1);
return 0;
}
|
No comments:
Post a Comment