Help with string programming logic?

Asked

Viewed 107 times

1

I’m new to this string area and I’m having a hard time. My algorithm should find and return the first time of the key(which the user enters) in the string, otherwise -1 must be returned. q is wrong in my function?

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

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

    while(str[i]!='\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;
}
  • Is returning some error?

  • @Inhares is not, but if I type for example 'hi' and informs key as 'k', it speaks q is inside the string, ta always informing q this to qlqr key q informo

3 answers

4


There are several small errors in your program:

  • The if to show the result is switched:

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

    The return that leaves the function is 0 when it does not exist, but in if the 0 writes that "The given character exists in the string", so you must swap the two printfs.

  • The character reading is not correct:

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

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

    By switching to %c will create another problem in relation to the previous reading of scanf("%[^\n]s" because the line break itself has not been consumed. To solve both without complicating can do so:

    scanf(" %c",&chave);
    

    Where space consumes previous line break.

  • The for to find the character is also not correct:

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

    Here the beginning of (comp; is reductive and does nothing, so you can remove it. Then you use the i to access the position and fetch the letter then the i has to increase and not the comp decrease. Also, you are not considering the case where you do not find the letter in the order condition str[i] != chave that can leave you wandering the memory infinitely.

    Correct would be:

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

    That makes it even simpler.

See your fixed code working on Ideone

Reinvent the wheel

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

  • str_length - There is already a native function to get the size of string calling for strlen,

  • All the logic your program is trying to make to find the first occurrence in a string already exists in the function strstr

To use the two functions I have indicated you need to include <string.h>, but your program gets 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 also this example in Ideone

  • Very good answer

  • Thanks for the tips of functions that the bilbioteca string. h has, but can not use any kkk. I need to make a logic without using these functions of the library, but see here for the tips

1

You can simplify the search in the function str_chave using the variable i to control the position being searched, and return it when it finds. 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 done, just change to show the returned Dice 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);
  • It worked out, thanks bro, simple thing of if fzr and me here breaking the head kkkkk

0

As it is a single character:

 scanf("%s",&chave);

for:

 scanf("%c", &chave);

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

  • I switched, but now I’m not letting nor I inform the 'key', I better leave the %s same.

  • I think it is better to study the meaning of %s and %c in the scanf function. You also changed the char key definition (a character) to a 2 position string, in which case you cannot use the == operator for equality.

Browser other questions tagged

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