u

Friday, 14 September 2012

C++ Program to delete the first common word in two strings and display the strings without the first common words

C++ Program to delete  the first common word in two strings and display the strings without the first common words

#include <conio.h>
#include <stdio.h>
#include <iostream.h>

char string1[25] = {'\0'};
char string2[25] = {'\0'};
char temp[25] = {'\0'};

int start = -1;
int end = -1;

int start2 = 0;
int end2 = 0;


/*GET THE INPUT FOR THE STRINGS*/
void get_input()
{
    cout << "Enter the first string : ";
    gets(string1);

    cout << "Enter the second string : ";
    gets(string2);
}


/*SET INDEXES FOR ALIAS WORD*/
void extract_word()
{
    while( string2[end2] != ' ' )
        end2++;
}


/*COMPARE THE TWO WORDS*/
int compare()
{
    int n;

    for(n=start; n<end; n++)
    {
        if( string2[n-start] != string1[n] )
        {
            return 0;
        }
    }
    return 1;
}


/*FIND THE ALIAS WORD IN THE STRINGS*/
void find_alias()
{
    int same = 0;

    while( (same != 1) && (string1[end] != '\0') )
    {
        end++;
        start = end;

        while( (string1[end] != ' ') && (string1[end] != '\0') )
            end++;

        same = compare();
    }

}

/*REPLACE THE WORD*/
void replace_alias()
{
    int counter = end;

    /*find the end of the string*/
    while( string1[counter] != '\0' )
        counter++;

    /*copy the remaining string to temp*/
    for(int i=end; i<counter; i++)
    {
        temp[i-end] = string1[i];
    }

    counter = start;

    /*nullify the remaining string*/
    while( string1[counter] != '\0' )
    {
        string1[counter] = '\0';
        counter++;
    }

    start2 = end2;
    counter = start-1;

    /*replace the alias by the second string*/
    while( string2[end2] != '\0' )
    {
        string1[counter] = string2[end2];
        end2++;
        counter++;
    }

    int k = 0;

    /*copy the remaining string back from temp*/
    while( temp[k] != '\0' )
    {
        string1[counter] = temp[k];
        k++;
        counter++;
    }
}


void main()
{
    clrscr();

    get_input();
    extract_word();
    find_alias();
    replace_alias();

    cout << string1 << '\n';

    getch();
} 

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More