Wednesday, 18 February 2015

Strings in c Language-2


A large set of c functions are provided with every c compiler.

Although it is a big list we shall discuss the functions Strlen(),strcpy(),strcat(),strcmp() ,because these are all the most used one.

strlren()
This function Counts the no of characters in a string.

Example

#include<stdio.h>
#include<conio.h>
#include<string.h>
void  main()
{
char name[]=”muthu”;
int l1,l2;
clrscr();
l1=strlen(name);
l2=strlen(“welcome”);
printf(“str=%s string length=%d\n”,name,l1);
printf(“str=%s string length=%d\n”,”welcome”,l2);
getch();
}

Output
Str=muthu  string length=5
Str=welcome,string length=7

Note we have included a header file string.h in the above program . to use a string function. This is a essential one.

strcpy:

This function will copy a string from one variable to another variable.

Example:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[]=”muthu”;
char name2;
clrscr();
strcpy(name2,name1);
printf(“name1=%s\n”,name1);
printf(“name2=%s\n”,name2);
getch();
}

Output:

name1=”muthu”
name2=”muthu”

strcat:

this function will append a string from one variable to another variable.

Example:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[30]=”muthu”;
char name[15]=” karthikeyan”;
clrscr();
strcat(name1,name2);
printf(“name1=%s\n”,name1);
printf(“name2=%s\n”,name2);
getch();
}

Output:
name1=muthu karthikeyan
name2=muthu

strcmp:

this function will compare one string with other string to find out whether they are same or not. If two strings are identical strcmp function will return zero. If they are not  it will return the difference between  ASCII values of first non matching character.

Example:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[]=”muthu”;
char name2[]=”karthikeyan”
int i;
i=strcmp(name1,name2);
printf(“%d”,i);
getch();
}

Output:
2
This is the end of 2 part series string in c language:
please all visit my following blogs:







No comments:

Post a Comment