Strings in C programming strcmp(), strstr(), strlen()
Explain string and its different functions with examples
What is string?
Collection of char is known as string in C programming. The number of character any string contains is known as is its length.
And every string is termincated by null character i.e '\0'.
Syntax to declare string in C is :-
char str[10];
here str is string which can contain at most 10 character inluding null character '\0'
Function related to string -
strlen() - this function returns length of any string
strcmp() - this function compares two strings
strstr() - this function check if string contains substring
/* Example of strlen() */
#include<stdio.h>
#include<string.h>
int main()
{
char str[10] ="Hello";
int len;
len = strlen(str);
printf("\n Length of string is : %d ", len);
return 0;
}
*/ Example of strcmp() */
#include<stdio.h>
#include<string.h>
int main()
{
char str[10] ="Hello";
int len;
if(strcmp(str, "Hello") == 0)
{
printf("\n String are same");
}
else
{
printf("\n String are not same");
}
return 0;
}
/* Example of strstr() */
#include<stdio.h>
#include<string.h>
int main()
{
char str[10] ="Hello";
int len;
if(strstr(str, "Hell"))
{
printf("\n String contains Hell");
}
else
{
printf("\n String doesn't contain Hell");
}
return 0;
}
/* Display only even digits from given number */
#include<stdio.h>
int main()
{
int no;
printf("\n Enter any no :");
scanf("%d",&no);
while(no != 0)
{
if( (no%10)%2 ==0)
printf(" %d ", no%10);
no = no /10;
}
return 0;
}