Help in string programming logic?

1

I'm new to this string area and I'm having a hard time. My algorithm must find and return the index of the first occurrence of the key (that the user types) in the string, otherwise it should return -1. What is wrong with my function?

#include <stdio.h>  
#include <math.h>  
#define MAX 100  

int str_length(char str[])    
{  
    int i =0;  

    while(str[i]!='
#include <stdio.h>  
#include <math.h>  
#define MAX 100  

int str_length(char str[])    
{  
    int i =0;  

    while(str[i]!='%pre%')  
    {  
        i++;  
    }  

    return i;
}

int str_chave(char str[], int comp)
{
    int i=0;
    char chave;

    printf("Informe um caractere: ");
    scanf("%s",&chave);

    for (comp; str[i] != chave; comp--)
    {

        if(str[i]==chave)
        {
            return 1;
        }
        str[i]--;

    }
return 0;

}

int main()  
{  
    char string[MAX];  
    int comp,res,resi,chave;
    long long int n;
    long long int number;

    printf("Digite uma string: ");
    scanf("%[^\n]s",string);

    comp = str_length(string);

    printf("Comprimento de '%s': %d\n",string,comp);

     chave=str_chave(string,comp);
        if(chave==0)
            printf("O caractere informado existe na string.\n");
        else
            printf("O caractere informado nao existe na string.\n");

    return 0;
}
') { i++; } return i; } int str_chave(char str[], int comp) { int i=0; char chave; printf("Informe um caractere: "); scanf("%s",&chave); for (comp; str[i] != chave; comp--) { if(str[i]==chave) { return 1; } str[i]--; } return 0; } int main() { char string[MAX]; int comp,res,resi,chave; long long int n; long long int number; printf("Digite uma string: "); scanf("%[^\n]s",string); comp = str_length(string); printf("Comprimento de '%s': %d\n",string,comp); chave=str_chave(string,comp); if(chave==0) printf("O caractere informado existe na string.\n"); else printf("O caractere informado nao existe na string.\n"); return 0; }
    
asked by anonymous 13.06.2018 / 20:25

3 answers

4

There are several small bugs in your program:

  • The if to show the result is changed:

    if(chave==0)
        printf("O caractere informado existe na string.\n");
    else
        printf("O caractere informado nao existe na string.\n");
    

    The return that exits the function is 0 when it does not exist, but in if 0 writes that "The character entered exists in the string", so you should change the two printfs .

  • The caratere reading to look for is not correct:

    printf("Informe um caractere: ");
    scanf("%s",&chave);
    

    If it is a caratere it should be read with %c , otherwise the program will try to put the terminator string due to being %c and will do it in a memory space that does not belong to it, creating a bug subtle, which may appear later.

    Switching to scanf("%[^\n]s" will create another problem compared to the previous reading of for since the line break itself was not consumed. To solve the two without complicating can do so:

    scanf(" %c",&chave);
    

    Where space consumes the previous line break.

  • The (comp; for caratere search is also not correct:

    for (comp; str[i] != chave; comp--)
    {
        if(str[i]==chave)
        {
            return 1;
        }
       str[i]--;
    }
    

    Here the start of i is reduable and does nothing, so you can remove it. Then use i to access position and fetch the letter so comp has to increase and not str[i] != chave decrease. In addition, you are not considering the case where you can not find the letter in the str_length ending condition that can let you scroll infinitely.

    Correct would be:

    for (; i < comp; i++) {
        if(str[i] == chave) {
            return 1;
        }
    }
    

    That's even simpler.

See your corrected code working on Ideone

Reinventing the wheel

I know that in C we often have to reinvent the wheel, but in your case you are doing it more than you would need, and unless it is for educational purposes you should avoid it.

  • string - A native function already exists to get the size of strlen called strstr ,

  • All the logic your program is trying to find the first occurrence in a string already exists in the <string.h>

To use both of the functions I've indicated, you need to include %code% , but your program is much shorter and simpler:

#include <stdio.h>
#include <string.h> //nova inclusão aqui
#define MAX 100

int main() {
    char string[MAX];
    printf("Digite uma string: ");
    scanf("%[^\n]s",string);
    int comp = strlen(string); //comprimento com strlen
    printf("Comprimento de '%s': %d\n", string, comp);

    printf("Informe um caractere: ");
    char chave[2];
    scanf("%s",chave); //leitura como string pois é necessário para o strstr

    if(!strstr(string, chave)) //achar ocorrencia com strstr
        printf("O caractere informado nao existe na string.\n");
    else
        printf("O caractere informado existe na string.\n");

    return 0;
}

See this example on Ideone

    
13.06.2018 / 21:30
1

You can simplify the search in the str_chave function by using the i variable to control the position being searched, and return it when you find it. For example:

for (i; i < comp; i++)
{
    if(str[i]==chave)
    {
        return i+1; //O indice comeca em 0, mas queremos a posicao com base 1
    }
}
return 0;

Once this is done, just change to show the returned index on screen:

if(chave==0)
    printf("O caractere informado nao existe na string\n");
else
    printf("O caractere informado existe na string, posicao: %d.\n", chave);
    
13.06.2018 / 20:41
0

As a single character switch:

 scanf("%s",&chave);

by:

 scanf("%c", &chave);

Note that you will have problems if the key does not exist in the string and there is also a confusion between the variable i and the comp variable.

    
13.06.2018 / 20:35