Calculate lexicographically letter of a string

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 equal the first would go to the next letter. If all letters are equal, it would return 0. But it is always returning l2 . Am I doing the wrong calculation?

My code:

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

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

    while(str1[i] != '%pre%' && str2[i] != '%pre%')
    {
        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");

}
' && str2[i] != '%pre%') { 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"); }
    
asked by anonymous 15.06.2018 / 20:49

1 answer

5

You go through the strings only once, so it does not make sense to have two while loops.

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

Here is 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 output:

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

See here working on ideone.

Note that && str1[i] != 0 only checks if one of the strings is gone. This happens because what is after && will only be evaluated when the strings have different content, so what is after && will only be evaluated in cases where either or both have ended or both have not ended. So, to detect the case where both ends, just check one.

    
15.06.2018 / 21:12