similarity of two strings

please correct this code to check the similarity of two strings.

#include<iostream.h>
#include <conio.h>
#include <stdio.h>
using namespace std;

int main()
{char st1[50], st2[50];
float len1(char *);
float len2(char *);
float num;
int i=0, j=0;
cout<<"enter st1 = "; cin>>st1;
cout<<"\nenter st2 = "; cin>>st2;

cout<<"\nlen st1 = "<<len1(st1);
cout<<"\nlen st2 = "<<len2(st2);

float tlen = len1(st1) + len2(st2);
cout<<"\ntotal len = "<<tlen;
char *ptr1, *ptr2;
ptr1= st1;
ptr2= st2;
num = 0;
for (i=0;*ptr1!='\0';i++)
{
for (j=0;*ptr2!='\0';j++)
{
if (*ptr1 == *ptr2)
{ num++; }
else
{ break; }

*ptr2++; }

*ptr1++; }
cout<<"\n\nsame ="<<num;

float res = (num/tlen)*100.0;
cout<<"\n\nresemblance = "<<res;

getch();
}
float len1(char *sss)
{
int c=0;
while (*sss!='\0')
{
c++;
*sss++;
}

return c;
}
float len2(char *ppp)
{
int d=0;
while (*ppp!='\0')
{
d++;
*ppp++;
}

return d;
}


Put the code you need help with here.


for (i=0;*ptr1!='\0';i++)
{
for (j=0;*ptr2!='\0';j++)
{
if (*ptr1 == *ptr2)
{ num++; }
else
{ break; }

*ptr2++; }

*ptr1++; }
cout<<"\n\nsame ="<<num;

float res = (num/tlen)*100.0;
cout<<"\n\nsimilarity = "<<res;

len1 and len2 do exactly the same thing. The same code with different variable names does not differ in any significant way.

1
2
3
4
5
6
7
8
9
10
11
float len1(char *sss)
{
    int c=0;
    while (*sss!='\0')
    {
        c++;
        *sss++;
    }

    return c;
}


What I'm wondering is why you're returning a float type? Do you expect that the length may be negative or some fractional value of a whole number at some point? What is the significance of the asterisk on line 7?

Presumably you have some algorithm for determining similarity. Currently all you are doing is checking if the beginning of the strings are the same, so what you need to do to fix that is make your code conform to the algorithm you should be using.

Well if I was checking the similarity, I would do it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>


using namespace std;

int main()
{

    string a,b;
    int incmn = 0;
    int vSz;
    cout << "Enter two strings:" << endl;
    cin >> a >> b;
    if(a == b)
        cout << "100% Similarity!";
    else{
            if(a > b)
             vSz = b.size();
        else
             vSz = a.size();

        for(int i = 0; i != (vSz);++i){
            if(a[i] == b[i])
                ++incmn;}
        }
    cout << "Strings have " << incmn << " characters in common. " << a 
            << " is " << a.size() << " characters long and " << b << " is " 
            << b.size() << " long." << endl;
return 0;

}


you can convert incmn to percentage
Topic archived. No new replies allowed.