HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

String comparison using pointers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pointersstringusingcomparison

Problem

This piece of code works fine. But I'm wondering if it can be done in a more efficient way. More specifically, this part ((s1 + i)) if it possible to force it to sequence through entire array character by character via pointer, for example, s1++.

My task to do this function compareStrings without index array []:

int  compareStrings(const char  *s1, const char  *s2)
{
    int i = 0, answer;
    //  i - to sequence through array of characters
    // pointer to character string1 and character string2
    while (*(s1 + i) == *(s2 + i) && *(s1 + i) != '\0'&& *(s2 + i) != '\0')
    {
        i++;
    }

    if ( *(s1 + i)  s2  */

        return answer;


But I want to change it to s1++ and s2++ instead of (s1 + i) and (s2 + i). I've tried to implement this idea with pining an extra pointer to the beginning but I've failed.

int  compareStrings(const char  *s1, const char  *s2)
{
  int answer;
  char **i = s1, **j = s2;
  // i to sequence through array of characters
  while (*(i++) == *(j++) && *(i++) != '\0'&& *(j++) != '\0');

  if (*i  s2  */

  return answer;
}

Solution

You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != '\0' && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }

    if (*s1 == *s2)
    {
        return 0;
    }

    return *s1 < *s2 ? -1 : 1;
}


Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.

Code Snippets

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != '\0' && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }

    if (*s1 == *s2)
    {
        return 0;
    }

    return *s1 < *s2 ? -1 : 1;
}

Context

StackExchange Code Review Q#154347, answer score: 17

Revisions (0)

No revisions yet.