Tuesday, 12 April 2016

C And C++ Program to compare two strings Problem Solution.


C Solution:

#include <stdio.h>
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    char str1[1000], str2[1000];
    int res = 0,i = 0;

    printf("Enter first string: ");
    gets(str1);
    printf("Enter second string: ");
    gets(str2);

    while(str1[i] != '\0' && str2[i] != '\0'){
        if(str1[i] < str2[i]){
            res = -1;
            break;
        }
        else if(str1[i] > str2[i]){
            res = 1;
            break;
        }
        i++;
    }

    if(res == 0) printf("\nBoth strings are equal.\n");
    else if(res == -1) printf("\nFirst string is lexicographically smaller than second string.\n");
    else  printf("\nFirst string is lexicographically greater than second string.\n");

    return 0;
}

C++ Solution:

#include <iostream>
using namespace std;
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    string str1, str2;
    int res = 0,i = 0;

    cout << "Enter first string: ";
    getline(cin,str1);
    cout << "Enter second string: ";
    getline(cin,str2);

    while(str1[i] != '\0' && str2[i] != '\0'){
        if(str1[i] < str2[i]){
            res = -1;
            break;
        }
        else if(str1[i] > str2[i]){
            res = 1;
            break;
        }
        i++;
    }

    if(res == 0) cout << endl << "Both strings are equal." << endl;
    else if(res == -1) cout << endl << "First string is lexicographically smaller than second string." << endl;
    else  cout << endl << "First string is lexicographically greater than second string." << endl;

    return 0;
}

No comments:

Post a Comment