Lexicographically compute the letter of a string

Asked

Viewed 96 times

3

My function needs to lexicographically calculate the value of the characters (by the ASCII table) of the string. For example:

"Alibaba" and "Came"
'A' = 65 and 'V' = 86
65 - 86 = -21.

Then the function would return l1 and if it were the same as the first letter it would go to the next letter. If all letters are equal, it would return 0. But it is always returning l2. I’m making the wrong calculation?

My code:

void str_comparacao(char str1[], char str2[]) 
{   
    int i=0;  
    int y;  

    while(str1[i] != '\0' && str2[i] != '\0')
    {
        while(str1[i] != str2[i])
        {

            if(str1[i]==str2[i])
            {
                y=str1[i]-str2[i];
            }
            i++;    
        }
        i++;
    }

    if(y<0)
    printf("L1, str1 < str2\n");
    else
    printf("L2, str1 > str2\n");

}

1 answer

5


You scroll through the strings only once, so it doesn’t make sense to have two loops while.

All this can be solved with a for. You go through the two strings together until you find a different letter or until they’re gone.

See here the resulting code:

int str_comparacao(char str1[], char str2[]) {
    int i;
    for (i = 0; str1[i] == str2[i] && str1[i] != 0; i++) {}
    return str1[i] - str2[i];
}

void teste(char str1[], char str2[]) {
    int resultado = str_comparacao(str1, str2);
    char c = resultado < 0 ? '<' : resultado > 0 ? '>' : '=';
    printf("%s %c %s\n", str1, c, str2);
}

int main() {
    teste("Vermelho", "Verde");
    teste("Verde", "Verde");
    teste("Verde", "Vermelho");
    teste("Verde", "Cinza");
    teste("Cinza", "Verde");
}

Here’s the way out:

Vermelho > Verde
Verde = Verde
Verde < Vermelho
Verde > Cinza
Cinza < Verde

See here working on ideone.

Note that the && str1[i] != 0 only checks if one of the strings is finished. This is because what is after the && will only be evaluated when the strings have different content, and therefore what is after the && will only be evaluated in cases where either both ended or both ended. Therefore, to detect the case where both ended, just check one of them.

  • Thank you, but I was wondering how you would do that in writing. Type like this, the 'V' of red and green are equal, then went to the next letter and so on, until arriving in a different letter and calculating the difference between the values of the letters, understood?

  • 1

    @Yes, I understand, and that’s exactly what this code does!

  • A is, I did the wrong example kkkk, thanks bro, helped mto <3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.