How to compare a string position to a? C character

Asked

Viewed 902 times

-1

The parse_names function is not able to compare the position of the string 'a' with a letter, I want to count how many letters 'A' appear in the string and exchange the letters 'E' for a 3 .

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int processa_nomes(char a[3][30])
{

    int i, j, cont=0;

    for(i=0; i<3; i++)
    {
        for(j=0; j<30; j++)
        {
            if(a[i][j]=='E')
            {
                a[i][j]= 3;
            }
        }

    }

    for(i=0; i<3; i++)
    {
        printf("Nome: %s \n", a[i]);
    }

    for(i=0; i<3; i++)
    {
        for(j=0; j<30; j++)
        {
            if(a[i][j]=='A')
            {
                cont++;
            }
        }



   }

    return cont;
}

int main()
{
    int i;
    char a[3][30];

    for(i=0; i<3; i++)
    {
        printf("Digite um nome: ");
        gets(a[i]);
    }

    printf("\nQuantidade de letras 'A' na string: %d\n", processa_nomes(a));

    return 0;
}
  • Note that[i] is not a character but the address for a string of up to 30 characters. If you want to compare strings use the strcmp function of <string. h>.

  • But how do I check, for example, how many letters 'A' has in each string ?

  • If you want to compare each of the 3 strings then use one for the number of strings and another for the number of characters of each string and then use an if almost as you used: if(a[i][j]='E'). Now I do not understand what you want to do when it is equal in the case of the letter 'E' in the case of the letter 'A' all right.

  • In the case of the letter 'E', each time it appears I wish to exchange it for the number 3

  • Then use[i][j] = '3';. Character '3' and not number 3, as it is an array of characters.

  • Now it’s worked out, thanks !!

Show 1 more comment

1 answer

1

As the answer was eventually given comments, I will put it here for future references. Also decreasing the number of loops:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int processa_nomes(char a[3][30])
{

    int i, j, cont=0;

    for(i=0; i<3; i++)
    {
        for(j=0; j<30; j++) {
            if(a[i][j]=='E') {
                a[i][j]= '3';
            } else if(a[i][j]=='A') {
                cont++;
            }
        }
        printf("Nome: %s \n", a[i]);
    }

    return cont;
}

int main()
{
    int i;
    char a[3][30];

    for(i=0; i<3; i++)
    {
        printf("Digite um nome: ");
        gets(a[i]);
    }

    printf("\nQuantidade de letras 'A' na string: %d\n", processa_nomes(a));

    return 0;
}

Browser other questions tagged

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