String Comparison

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madhankrish
    New Member
    • Dec 2006
    • 16

    String Comparison

    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
  • prakash ravindran
    New Member
    • Dec 2006
    • 10

    #2
    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<((str 1len>str2len)?s tr1len:str2len) ;i++)
    {
    if(*str1!=*str2 )
    count++;
    str1++;
    str2++;

    }
    printf("%d",cou nt) ;
    return ;
    }
    note :
    read the string str1 and str2 from the file....

    Comment

    • madhankrish
      New Member
      • Dec 2006
      • 16

      #3
      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

      Comment

      • prakash ravindran
        New Member
        • Dec 2006
        • 10

        #4
        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,line len, file);
        fgets(str2,line len, file);
        }
        fclose(file);
        try this it must work....


        regards

        Prakash R.

        Comment

        • madhankrish
          New Member
          • Dec 2006
          • 16

          #5
          Thankyou so much Prakash.
          You seem to help me out everytime :-)

          Regards,
          Madhan

          Comment

          Working...