Tuesday 24 June 2014

C++ program to delete all consonants from a string

Here is a C++ program to delete all consonants from a string. Here I have given 4 methods to delete consonants. First method simply replaces consonants with space, second method replaces consonants with the next character in string and third and fourth method shows how we can delete consonants using function or recursion.



Method 1 : C++ program to delete all consonants from a string
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str[100];
    cout<<"Enter string : ";
    cin>>str;
    for(int i=0;str[i]!='\0';i++)
    {
        if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'
            ||str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
            continue;
        str[i]=' ';
    }
    cout<<"After deleting consonants : "<<str;
    return 0;
}




Method 2 : C++ program to delete all consonants from a string
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str[100];
    cout<<"Enter string : ";
    cin>>str;
    for(int i=0;str[i]!='\0';i++)
    {
       if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'
            ||str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
            continue;
        for(int k=i;str[k]!='\0';k++)
                      str[k]=str[k+1];
         i--;

    }
    cout<<"After deleting consonants : "<<str;
    return 0;
}





Method 3 : C++ program to delete all consonants from a string using function
#include<iostream>
#include<string.h>
using namespace std;
void dcon(char (&a)[100])
{
    for(int i=0;a[i]!='\0';i++)
    {
       if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'
            ||a[i]=='A'||a[i]=='E'||a[i]=='I'||a[i]=='O'||a[i]=='U')
            continue;
       for(int k=i;a[k]!='\0';k++)
           a[k]=a[k+1];
       i--;
    }
}
int main()
{
    char str[100];
    cout<<"Enter string : ";
    cin>>str;
    dcon(str);
    cout<<"After deleting consonants : "<<str;
    return 0;
}



Method 4 : C++ program to delete all consonants from a string using recursion
#include<iostream>
#include<string.h>
using namespace std;
void dcon(char (&a)[100],int i)
{
    if(a[i]==0)
        return;
    if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'
        ||a[i]=='A'||a[i]=='E'||a[i]=='I'||a[i]=='O'||a[i]=='U');
    else
        a[i]=' ';
    dcon(a,i+1);
}
int main()
{
    char str[100];
    cout<<"Enter string : ";
    cin>>str;
    dcon(str,0);
    cout<<"After deleting consonants : "<<str;
    return 0;
}




No comments:

Post a Comment