String comparision

Posted on 2003-02-21
Medium Priority
Last Modified: 2010-04-15
I am new to c programming. I need to write own code for comparing two strings in C and not use inbuilt strcmp function. Can someone please help me with this.
Question by:Leafox
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 22

Expert Comment

ID: 7994639
Here's a huge hint:

start with i = 0;
compare str1[ i ] with str2[ i ].

if they're both '\0', then the strings are equal, return 0.

if they're not '\0', and  equal, move on to the next character (i+1)

now we've found two unequal characters at position i.

if the first one is > the second one, return +1
otherwise return -1.

That's pretty much it.


Accepted Solution

codez80 earned 200 total points
ID: 7995939
you can do it like this:

int string_compare(const char* str1, const char* str2)
  int i;

  i = strlen(str1) - strlen(str2);

  if (i != 0)
     return i;

  while (*str1)
     i = *str1 - *str2;
     if (i != 0)
        return i;
  return 0;

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question