Question:
C programing compare two strings?
Himanshu Gajwani
2011-11-14 10:05:15 UTC
Ok so my prof gave me this Q.

Write a program to enter two string and compare them without using any standard function. Determine whether the string are identical or not. also display the number of position where the character are different.

First of all DON'T GIVE ME THE CODE. I want to do it by my self just guide me how to do.
What i am thinking is if I can get the asacii equivalent of string the we can compare it. Point me if i am wrong.

Just guide me how to do.
Three answers:
anonymous
2011-11-14 11:43:59 UTC
Algorithm for your advice:



1. Enter two strings

2. Compare its length with each other

3. If length of strings are equal proceed to step 4 else exit.

4. Now start a loop till the length of the string.

5. Compare each element using indexes of that character value. such as char a[5],b[5] then you can use it like a[1] = b[1].

6. you have to compare the same indexes on the both arrays as only then the string arrays would be equal to each other.

7. Set a flag in between the condition u put inside the look, if value don't comes equal at any index then set the flag = 0 and break out of the loop.

8. Check the value of the flag and if flag= 0, print the strings are not equal and exit.

9. Check the value of the flag and if flag= 1, print the strings are equal and exit.



Ankit

http://www.outperformtechnologies.com
oops
2011-11-14 18:10:31 UTC
What does it mean to get the ASCII equivalent? Characters are stored(on most implementations) as ASCII (or utf-8, of which ASCII is a subset), so there's nothing to 'get', it's already there. You can compare characters directly, in a for loop. Be sure to test for the null terminator('\0' or simply 0) to know when the string is ended.
shubham.science
2011-11-14 18:30:38 UTC
getting the ascii equivalent is very tedious. I give you a very simple procedure.

1. Get two strings from user.

2. Get size of two strings and proceed only if they are equal.

3. Using for loop, check position by position.

4. If step 3 results true, then the strings are identical else they are not.

CODING:

char ch[30], ch1[30];

cout<<"Enter the strings:";

gets(ch);

gets(ch1);

int size=strlen(ch);

int size1=strlen(ch1);

int flag=0; int position;

if(size==size1)

{

for (int i=0; i<30; i++)

{

if (ch[i]==ch1[i])

flag++;

else{position=i+1;

break;

}

}

}

else { cout<<"strings cannot be compared"; exit(0);}

if (flag==size)

cout<<"strings are identical";

else cout<<"strings are not identical and they differ at position:"<
getch();

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...