By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,136 Members | 1,204 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,136 IT Pros & Developers. It's quick & easy.

String Comparison

P: 16
hello all,
i'm writing code in c.
can someone help me out with this problem?
i have to read the first line of a text file into string1.
the second line has to be read into string2.
then strings 1 and 2 have to be compared character by character..
and the number of differences between the 2 strings has to be printed.
can someone give me the code?
thanks

madhan
Dec 26 '06 #1
Share this Question
Share on Google+
4 Replies


P: 10
hii


This may help u out...

int main(void)
{
char *str1="hi";
char *str2="happy";

int str1len ;
int str2len ;
int i ;
int count =0 ;

str1len = strlen(str1);
str2len = strlen(str2);


for(i=0;i<((str1len>str2len)?str1len:str2len);i++)
{
if(*str1!=*str2)
count++;
str1++;
str2++;

}
printf("%d",count) ;
return ;
}
note :
read the string str1 and str2 from the file....
Dec 26 '06 #2

P: 16
thankyou prakash.
its working fine.
but in my case, i have to read the first line of a file as str1 and the second line of the same file as str2.
that is exactly what i wanted to know.
hope u could help me out.
thanks again.

madhan
Dec 27 '06 #3

P: 10
madhan,

It is not big work to call a file and read the first line and 2nd line alone

use fgets() function to read the data from the file.

FILE *file;
file = fopen("test.txt", "r");

if(file==NULL)
{
printf("Error: can't open file.\n");
return 1;
}
else
{
fgets(str1,linelen, file);
fgets(str2,linelen, file);
}
fclose(file);
try this it must work....


regards

Prakash R.
Dec 27 '06 #4

P: 16
Thankyou so much Prakash.
You seem to help me out everytime :-)

Regards,
Madhan
Dec 27 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.