Wednesday, 2 April 2014

programs on Strings

Program to reverse the order of words in a sentence

example: 
Input: my name is aravind
output: aravind is name my

#include<stdio.h>
#include<string.h>
main()
{
int i,j,k,l,m;
char a[40],temp;
printf("enter the sentence\n");
gets(a);
k=strlen(a);
for(i=0;i<k/2;i++)
{
temp=a[i];
a[i]=a[k-i-1];
a[k-i-1]=temp;
}
a[k]=' ';
i=0;
while(i<k)
{
j=i;
while(a[i]!=' ')
i++;
l=i-1;
for(m=0;m<(l-j+1)/2;m++)
{
temp=a[j+m];
a[j+m]=a[l-m];
a[l-m]=temp;
}
i++;
}
for(i=0;i<k;i++)
printf("%c",a[i]);
printf("\n");
}


TC = Θ(n)
SC = O(1)

Count vowels/consonants in a string. 

example: "alpha" as input and output is 2, 3

void count(char a[], int b[])
{
int i;
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u')
b[0]++;
else
b[1]++;
}
}

Change case of every character (lower to uppper and upper to lower). 

example: input: AlpHa and output is aLPhA

void convert(char a[])
{
int i;
for(i=0;a[i]!='\0';i++)
{
if(a[i]<='Z'&&a[i]>='A')
a[i]=a[i]-'A'+'a';
else
a[i]=a[i]-'a'+'A';
}
}

Using standard phone mapping convert a string to a number representation. 

example: Input: cat and output: 228

void convert(char a[],char b[])

{
int i;
for(i=0;a[i]!='\0';i++)
{
b[i]=numberofchar(a[i]);
}
b[i]='\0';
}

char numberofchar(char c)
{
if(c=='a'||c=='b'||c=='c')
return '2';
if(c=='d'||c=='e'||c=='f')
return '3';
if(c=='g'||c=='h'||c=='i')
return '4';
if(c=='j'||c=='k'||c=='l')
return '5';
if(c=='m'||c=='n'||c=='o')
return '6';
if(c=='p'||c=='q'||c=='r'||c=='s')
return '7';
if(c=='t'||c=='u'||c=='v')
return '8';
if(c=='w'||c=='x'||c=='y'||c=='z')
return '9';

}

Given (abc, 2) -> abcabc. Repeat whole string two times one after another.

void repeatstring(char a[],int n)
{
int i,j,k=0;
char b[20];\\temporary array to store the given array
for(i=0;a[i]!='\0';i++)
b[i]=a[i];
b[i]='\0';
for(i=0;i<n;i++)
for(j=0;b[j]!='\0';j++)
a[k++]=b[j];
a[k]='\0';
}

Given (abc, 2) -> aabbcc. Repeat each char and Expand the string. 

void repeatchar(char a[],int n)
{
int i,j,m=0;
char b[100]; \\temporary array  to store the given string
for(i=0;a[i]!='\0';i++)
b[i]=a[i];
b[i]='\0';
for(i=0;b[i]!='\0';i++)
for(j=0;j<n;j++)
a[m++]=b[i];
a[m]='\0';

}

Remove all digits in a given string

void removedigits(char a[])
{
int i,j=0;
for(i=0;a[i]!='\0';i++)
{
if(a[i]<'0'|| a[i]>'9')
{
a[j++]=a[i];
}
}
a[j]='\0';

}

No comments:

Post a Comment