Char comparison, ignoring case sensitive

4

The proposal is to create a program that compares the n positions of the two vectors and returns whether they are equal or not. So far so good, but I do not know how I can ignore 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;
}
    
asked by anonymous 09.07.2016 / 03:10

1 answer

6

Just use the tolower() function to get everything small. I took and improved some things, for example give a more meaningful name to the function and does not overlap an existing one 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 ");
    return 0;
}

See working on ideone and on CodingGround .

You can further simplify the comparison:

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

See working on ideone and on CodingGround .

If you do not 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;
}
    
09.07.2016 / 03:39