Results 1 to 16 of 16

Thread: strcmp() function implementation

  1. #1
    Sc0rp
    Guest

    Talking strcmp() function implementation

    Hey,

    How is the strcmp(char*, char*) implemented?
    I need to implement it myself for my Comp Science class, and this is what I got:
    PHP Code:
    int strcmp(const chars1, const chars2)
    {
        const 
    charp1 s1 1;
        const 
    charp2 s2 1;

        while (*++
    p2 == *++p1)
            if (!*
    p2 || !*p1)
                break;

        if (*
    p2 > *p1)
            return (-
    1);
        else if (*
    p1 > *p2)
            return (
    1);

        return (
    0);

    But it looks too long and clumsy for such a simple function.


    Thanks.

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    You're close.

    This is what's in the VC++ Runtime Library:
    Code:
    int __cdecl strcmp (
            const char * src,
            const char * dst
            )
    {
            int ret = 0 ;
    
            while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)
                    ++src, ++dst;
    
            if ( ret < 0 )
                    ret = -1 ;
            else if ( ret > 0 )
                    ret = 1 ;
    
            return( ret );
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3
    Fanatic Member MoMad's Avatar
    Join Date
    Oct 2000
    Location
    Seattle, WA
    Posts
    625
    Or better yet

    PHP Code:
    int strcmp(const chars1, const chars2) {
        
    int ret 0;

        while( !(
    ret = *(unsigned char*)s1 - *(unsigned char*)s2) && *s2 )
            ++
    s1, ++s2;

        return 
    ret != ? (ret : -1) : 0;

    BTW: The turnary opperator is my fav
    -MoMad
    :MoMad:
    Nice Sig!

    http://go.to/momad/ Status: Not Ready

  4. #4
    Zaei
    Guest
    That conditional makes it that much harder to read, with no extra speed =).

    Z.

  5. #5
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    The ternary operator is only good for changing the emphasis from the comparison, to the result. For example:
    Code:
    bool val = true;
    
    if(val) {
        cout << "true";
    } else {
        cout << "false";
    }
    
    cout << (val ? "true" : "false");
    The first way, the first thing you see is the comparison, but what's important is the fact that you're printing the value - the comparison is only a minor part of it (selecting the correct word to use).
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  6. #6
    Fanatic Member MoMad's Avatar
    Join Date
    Oct 2000
    Location
    Seattle, WA
    Posts
    625
    hey hey, hold on a sec!

    Look, there are times to use if/else and times to use the turnery operator:

    PHP Code:
    // try (1 line of code)
    printf"It is %d:%d %s\n"hm12 "AM" "PM" );

    // instead of: (6 lines)
    printf"It is %d:%d"h);

    if( 
    12 
       
    printf" AM\n");
    else
       
    printf" PM\n"); 
    The above strcmp example doesnt make any difference, but its completely valid, and hey, like the recruiting ppl say, the more complicated your code, the smarter ppl will think you are

    Anyways, I am saying that ternery operator is AWESOME!! Better than if/else but everything has its rightious moments. Parksie you are soooo right, and you too Zaei; this was not the right problem for a ternery operator, but I just wanted to show everyone how you can make your code as little as possible Like the while loop, it could have been done with for's and more writing but it was done with 2 lines instead of 10 or say 30, you see where im getting at??
    :MoMad:
    Nice Sig!

    http://go.to/momad/ Status: Not Ready

  7. #7
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221

    beauty of code

    Originally posted by MoMad
    but its completely valid, and hey, like the recruiting ppl say, the more complicated your code, the smarter ppl will think you are
    I would prefer the ternary operator for elegance purpose only, I find fachinating expressions with sideeffects a beauty. However, complex expressions are often a performance hit, so it's not too often, except for some pointer aritmetic when you get to use your l337ness for practical purposes as well

    But, I'm going to change that, when you realize the beauty of my expression templates
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  8. #8
    Fanatic Member MoMad's Avatar
    Join Date
    Oct 2000
    Location
    Seattle, WA
    Posts
    625
    Kedaman, Shout me a holla when you're done with that, will ya?? And hey, it depends on how you use it... I havent come across "side-effects" but then again, I dont "overdose" on the ternery operators... so when I do, ill let you all know.

    Aaaaagggghhhh, reading back, my spalling is ewfall!! Argggggg...
    :MoMad:
    Nice Sig!

    http://go.to/momad/ Status: Not Ready

  9. #9
    Sc0rp
    Guest
    Thanks a lot everybody.

  10. #10
    Sc0rp
    Guest
    Alright, that's my final version.
    The HEAVY HEAVY commenting is required by the testers.

    PHP Code:
    // -----------------------------------------------------
    // Function Name:   strcmp()
    //
    // Input:           Two strings to compare.
    //
    // Output:          (-1) the second string is bigger.
    //                  ( 1) the first string is bigger.
    //                  ( 0) the strings are identical.
    //
    // Operation:       The function receives two strings to
    //                  compare in dictionary-comparison, and
    //                  returns a flag according to which
    //                  string is bigger.
    // -----------------------------------------------------
    int strcmp(const charp1, const charp2)
    {
        
    // A variable to hold the distance in ASCII charcters
        // between the current two characters we're comparing.
        
    int dist 0;

        
    // Keep checking while the distance is 0, and we're
        // not hitting NULL on one of the strings.
        
    while (!dist && *p1 && *p2)
            
    // Get the distance while incrementing the
            // pointers to the next character.
            
    dist = (*p2++) - (*p1++);

        
    // Check the last distance and according to this
        // return (1) if the first string is bigger, (-1)
        // if the second string is bigger, or (0) if the
        // strings are identical.
        
    if (dist 0)
            return (-
    1);
        else if (
    dist 0)
            return (
    1);

        return (
    0);

    I didn't find any bugs, but if anyone does...

  11. #11
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    The javadoc style commenting is liked in a lot of commercial instances (Java, KDE, stuff like that), and it's in some ways easier to type:
    PHP Code:
    /** Compare two strings.
        \param p1 First string
        \param p2 Second string.

        \return A flag determining which string was bigger.
            \arg -1 the second string is bigger.
            \arg  1 the first string is bigger.
            \arg  0 the strings are identical.

        \remarks The function receives two strings to
            compare in dictionary-comparison, and
            returns a flag according to which
            string is bigger. */
    int strcmp(const charp1, const charp2) {
        
    // ...

    This is just one way of doing it though, some people prefer different styles
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  12. #12
    Fanatic Member MoMad's Avatar
    Join Date
    Oct 2000
    Location
    Seattle, WA
    Posts
    625
    Hey Parksi, isnt it like:

    @param string p1 - first string
    @return int - blah blah

    hmm... there are tons of different styles, but actually the way he has it is most popular among C/C++ programs and its even a standard at my school hehe I hear the Java commenting styles are also used by many php and perl programmers :P
    :MoMad:
    Nice Sig!

    http://go.to/momad/ Status: Not Ready

  13. #13
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    You're probably right.

    I use Doxygen though, which does @ and \. (I think \ is for Qt).

    I wasn't saying there was a problem with his, it's just you can't easily separate the documentation from the code with that style.

    www.doxygen.org
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  14. #14
    Fanatic Member MoMad's Avatar
    Join Date
    Oct 2000
    Location
    Seattle, WA
    Posts
    625
    Yes you are right...
    :MoMad:
    Nice Sig!

    http://go.to/momad/ Status: Not Ready

  15. #15
    New Member
    Join Date
    Jul 2009
    Posts
    1

    Re: strcmp() function implementation

    Here, nice and simple:

    int strcmp(char *str1, char *str2)
    {
    int i;
    for (i=0;str1[i]==str2[i];i++)
    if (str1[i] == '\0') return 0;
    return str1[i] - str2[i];
    }

  16. #16
    New Member
    Join Date
    Nov 2009
    Posts
    1

    Re: strcmp() function implementation

    Is it better..?

    int strcmp(const char* a, const char* b)
    {
    while(*a++ == *b++)
    if(*a == '\0' && *b == '\0') return 0;
    return -1;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width