Thread: Comparing two strings in C

  1. #1
    Banned
    Join Date
    Apr 2015
    Posts
    596

    Comparing two strings in C

    Hi; is there any function in C programming that's checking if two strings are identical ("having the same word/chars") or not?
    I have searched in google and there's a function called strcmp but it's working on the length of the strings not checking the chars itself!



    thanks in advance

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,056
    What do you think strcmp does if it's not comparing characters?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Banned
    Join Date
    Aug 2017
    Posts
    861
    but it's working on the length of the strings not checking the chars itself!
    Logic needs to be applied here.
    Process of elimination.
    How would I check for same string between two strings?
    first I'd check to be sure they are the same length before going further.
    if length equals same then check to be sure words match else it is not going to be the same then return results reflecting what you have found.

    you could use strlen to take care of the first part, then loop through your strings comparing them letter for letter to be sure they match, if no match, well you should know the rest.

    NetBSD strcmp source code
    Code:
    int
    strcmp(const char *s1, const char *s2)
    {
    
        _DIAGASSERT(s1 != NULL);
        _DIAGASSERT(s2 != NULL);
    
        while (*s1 == *s2++)
            if (*s1++ == 0)
                return (0);
        return (*(const unsigned char *)s1 - *(const unsigned char *)--s2);
    }
    Last edited by userxbw; 11-14-2017 at 08:59 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing Python strings to C strings
    By hinesro in forum C Programming
    Replies: 0
    Last Post: 11-29-2015, 09:14 PM
  2. Comparing strings?
    By jh294 in forum C Programming
    Replies: 5
    Last Post: 04-09-2011, 12:04 AM
  3. comparing strings in c
    By adel in forum C Programming
    Replies: 17
    Last Post: 02-14-2010, 01:33 PM
  4. comparing strings.
    By goran00 in forum C Programming
    Replies: 3
    Last Post: 04-20-2008, 08:18 AM
  5. comparing strings
    By GanglyLamb in forum C Programming
    Replies: 5
    Last Post: 11-03-2002, 08:01 AM

Tags for this Thread