Char comparison, ignoring the case sensitive

Asked

Viewed 1,072 times

4

The proposal is to create a program that compares n first positions of the two vectors and returns saying whether or not they are equal. So far so good, but I do not know how to ignore the case sensitive.

Here’s what I’ve done so far:

//Questão 7
#include <stdio.h>
#define MAX 5

int memcpy(char s1[], char s2[], int n);

int main()
{
    char s1_m[MAX]={'a', 'b', 'c', 'd', 'e'}, s2_m[MAX]={'a', 'b', 'c', 'D', 'E'};
    int n_m;

    printf("quantos caracteres serao verificados(max 5)\n> "); scanf("%d", &n_m); fflush(stdin);

    printf("os %d primeiros caracteres dos dois vetores %s iguais", n_m, memcpy(s1_m, s2_m, n_m)?"sao":"nao sao");
    return 0;
}

int memcpy(char s1[], char s2[], int n)
{
    int i, contador=0;

    for(i=0;i<n;i++)
    {
        if(s1[i]==s2[i])
            contador++;
        else
            break;
    }

    if(contador==n)
        i=1;
    else
        i=0;

    return i;
}
  • Did the posted answer solve your problem? Do you think you can accept it? If you don’t know how to do it, check out [tour]. This would help a lot to indicate that the solution presented was useful to you and to give an indication that it is satisfactory. You can also vote on any and all questions or answers you find useful on the entire site. Accepting and voting are separate things.

1 answer

6

Just use the function tolower() to take everything tiny. I took advantage and improved some things, for example give a more meaningful name to the function and that does not overlap one existing in C:

#include <stdio.h>
#include <ctype.h>
#define MAX 5

int comparacao(char s1[], char s2[], int n) {
    int contador = 0;
    for (int i = 0; i < n; i++) {
        if (tolower(s1[i]) == tolower(s2[i])) contador++;
        else break;
    }
    return contador == n;
}

int main() {
    char s1_m[MAX] = {'a', 'b', 'c', 'd', 'e'}, s2_m[MAX] = {'a', 'b', 'c', 'D', 'E'};
    int n_m;
    printf("quantos caracteres serao verificados(max 5)\n> "); scanf("%d", &n_m);
    printf("os %d primeiros caracteres dos dois vetores %ssao iguais", n_m, comparacao(s1_m, s2_m, n_m) ? "" : "nao ");
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Can further simplify the comparison:

int i = 0;
for (; i < n && tolower(s1[i]) == tolower(s2[i]); i++);
return i == n;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you don’t want to use the ready the function is more or less this:

int tolower(int c) {
    if (c <= 'Z' && c >= 'A') return c + 32
    return c;
}
  • Thank you very much. I had the idea that if I used tolower or toupper, it would modify the vector, but I tested it here in Code::Blocks and it’s working perfectly!

Browser other questions tagged

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