String handling functions:
1. strlen(): This function tells the number of character in a string. This will be as follows: l=strlen(string);
where l is integer.
2. strcat(): This function is use to combine two strings. This will be as follows:
strcat(string1,string2);
in this function the string2 is appended to string1 and it removes the ‘\0’ from string.
3. strcpy(): This function is use to copy the contents of string to another. This will be as follows:
strcpy(string1,string2);
this will copy the content of string2 to string1. And we can give string constant instead of character array.
e.g: strcpy(subject,”programming in c”);
4. strcmp(): This function is use to compare two strings. This will be as follows:
strcmp(string1,string2);
this will compare the both strings. And if they are equal this will return 0. Otherwise it will returns the numeric difference in both according to ASCII values.
Program:
PROGRAM TO SHOW INPUT AND OUTPUT OF A STRING
#include<stdio.h>
#include<conio.h>
void main()
{
char a[15];
clrscr();
printf(“Enter any string: “);
gets(a);
printf(“Inputted string is: “);
puts(a);
getch();
}
PROGRAM TO COMPARE TWO STRINGS WITHOUT USING STRING FUNCTION
#include<stdio.h>
#include<conio.h>
void main()
{
char a[10],b[10];
int i,count=0,count1=0,m;
clrscr();
printf(“Enter first string: “);
gets(a);
printf(“Enter second string: “);
gets(b);
i=0;
while(a[i]!=’\0′)
{
count++;
i++;
}
i=0;
while(b[i]!=’\0′)
{
count1++;
i++;
}
if(count==count1)
{
i=0;
m=0;
while(a[i]!=’\0′)
{
if(a[i]==b[i])
m++;
i++;
}
if(m==count)
printf(“Strings are equal”);
else
printf(“strings are not equal”);
}
else if(count>count1)
printf(“%s is larger than %s”,a,b);
else
printf(“%s is larger than %s”,b,a);
getch();
}
PROGRAM TO CONVERT A STRING FROM LOWER TO UPPER CASE
#include<stdio.h>
#include<conio.h>
void main()
{
int temp,len,i;
char a[10];
clrscr();
printf(“Enter any string in lower case: “);
gets(a);
len=strlen(a);
for(i=0;i<len;i++)
{
if(a[i]>=97 && a[i]<=122)
a[i]=a[i]-32;
}
printf(“After conversion upper string is: %s”,a);
getch();
}
PROGRAM TO SORT WORDS ALPHABETICALLY
#include<stdio.h>
#include<conio.h>
void main()
{
char a[10][20],temp[20];
int i,n,j;
clrscr();
printf(“Enter the size of array: “);
scanf(“%d”,&n);
printf(“Enter elements in the array:\n”);
for(i=0;i<n;i++)
{
scanf(“%s”,a[i]);
}
printf(“Entered array is:\n”);
for(i=0;i<n;i++)
{
printf(“%s”,a[i]);
printf(“\n”);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(a[i],a[j])>0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
}
printf(“After sorting array is:\n”);
for(i=0;i<n;i++)
printf(“%s\n”,a[i]);
getch();
}