Thread: making program for comparing strings.

  1. #1
    F#ck me Freddy!!
    Join Date
    Sep 2013
    Location
    jaipur
    Posts
    79

    making program for comparing strings.

    I know there is a function for comparing string but i am making it to just improve my concepts.
    error : 2 is coming as answer when i put same sting in both place.

    Code:
    #include<stdio.h>
    main()
    {
    char str1[] = "hello" ;
    char str2[]= "hello" ;
    int q;
    q = xstrcmp(str1,str2);
    printf("%d",q);
    }
    
    
    int xstrcmp(char *s1,char *s2)
    {
    while( *s1 != '\0' || s2 != '\0')
     {
     if (*s1 != *s2)
     {
      break;
     }
     s1= s1+1;
     s2=s2+1;
     }
     if ( *s1 == '\0' && *s2 == '\0')
      return(0);
     else if(*s1 == '\0' && *s2 != '\0')
      return(1);
     else if(*s1 != '\0' && *s2 == '\0')
      return(2);
     else if(*s1 != *s2)
     return(3);
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Code:
    while( *s1 != '\0' || s2 != '\0')
    One of these things is not like the other.

  3. #3
    F#ck me Freddy!!
    Join Date
    Sep 2013
    Location
    jaipur
    Posts
    79
    Thanx ..was a silly mistake .

  4. #4
    11DE784A SirPrattlepod's Avatar
    Join Date
    Aug 2013
    Posts
    485
    The while loop could be simplified... while (*s1 && *s1 != *s2)

  5. #5
    C lover
    Join Date
    Oct 2007
    Location
    Virginia
    Posts
    266
    Yeah, but code clarity is more important in my opinion (If it's to be shared with others anyways).

  6. #6
    11DE784A SirPrattlepod's Avatar
    Join Date
    Aug 2013
    Posts
    485
    Quote Originally Posted by Syscal View Post
    Yeah, but code clarity is more important in my opinion (If it's to be shared with others anyways).
    Interesting. I'd have thought the simplified condition was clearer, but *shrug* I'll put the break back
    Code:
    int xstrcmp(const char *s1, const char *s2)
    {
        unsigned char c1, c2;
        
        do {
            c1 = *s1++;
            c2 = *s2++;
            if (c1 == '\0')
                break;
        } while (c1 == c2);
    
        return c1 - c2;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing Strings
    By aplst3 in forum C Programming
    Replies: 27
    Last Post: 05-11-2010, 04:19 PM
  2. comparing strings in c
    By adel in forum C Programming
    Replies: 17
    Last Post: 02-14-2010, 01:33 PM
  3. comparing strings
    By Frantic- in forum C++ Programming
    Replies: 7
    Last Post: 12-12-2004, 12:38 PM
  4. comparing strings
    By infinitum in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2003, 12:10 PM
  5. Comparing 2 Strings
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 01-08-2002, 07:01 PM