Program in C, how to print the word without the character?

Asked

Viewed 861 times

-1

inserir a descrição da imagem aqui

I can’t print the word without the character and I have no idea how to execute the ending. if anyone can help

follow what I’ve done:

#include <stdio.h>
#include <string.h>
int main()
    {
    char frase[20], nova[20];
    char caracter[1];
    int x,y;
    printf("Informe a frase: ") ;
    fgets(frase, sizeof(frase), stdin);
    printf("Informe o Caracter: ");
    gets(caracter);

        for(x=0;x<=strlen(frase);x++)
        if(frase[x]!=caracter)
        nova[y++]=frase[x];

    printf("Frase remontada sem o caracter: %s", nova);

    return 0;
}
  • 1

    The statement gives the idea of substitution in the original string and not creation of a new one. It also mentions "remove (...) word" and not letter as it is in your code. You have to clarify these details ?

2 answers

0

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

int primeiraOcorrencia = 0;
char* f;
char* p;
char* m;
char* copiaF;
char frase[160];
char palavra[80];

int main(int argc, char* argv[])
{
    printf("Frase de entrada: ");
    fgets(frase, 160, stdin);
    printf("\n");
    printf("Palavra a ser retirada: ");
    scanf("%s", palavra);

    f = frase;
    p = palavra;

    primeiraOcorrencia = 1;

    while (*f)
    {
        if (*p != *f && *p != '\0')
        {
            primeiraOcorrencia = 1;
            p = palavra;
        }
        else
        {
            if (primeiraOcorrencia)
            {
                m = f;
                primeiraOcorrencia = 0;
            }

            if (!*p++)
            {
                copiaF = f;

                while (*copiaF)
                {
                    *m++ = *copiaF++;
                }
                *m = '\0';

                primeiraOcorrencia = 1;
                p = palavra;
            }
        }

        f++;
    }

    printf("Frase final sem a palavra: %s", frase);

    system("pause");
}

0

I assumed that you want to remove only one character from the sentence, if it is really a word you will need to make some changes.

You were using the variable y without initializing it and caracter as an array instead of just one char.

Below is the code with the necessary changes:

#include <stdio.h>
#include <string.h>
int main() {
  char frase[20], nova[20];
  char caracter;
  int x, y = 0;
  printf("Informe a frase: ") ;
  fgets(frase, sizeof(frase), stdin);
  printf("Informe o caracter: ");
  caracter = getchar();

  for (x = 0; x <= strlen(frase); x++)
    if (frase[x] != caracter)
      nova[y++] = frase[x];

  printf("Frase remontada sem o caracter: %s", nova);

  return 0;
}

Browser other questions tagged

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