String problem in C, term exclusion in string, through string comparison

Asked

Viewed 86 times

0

I wrote a code that excluded the similar term in both strings, but it does not print the result of the text by taking the second term, it only removes the first term from the first string.

"Create a program that receives a phrase and a term. If term is present in the sentence, remove it and print the sentence modified, otherwise, display "Term not found in phrase". Consider the maximum string size of 200."

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

int main()
{
    char texto[200];
    char word[10];
    int l1, ind, tam, j = 0, i, c = 0, r;

    scanf("%s", texto);
    gets(texto);
    scanf("%s", word);
    tam = strlen(texto);

    for (i = 0; i < l1; i++) {
      r = strcmp(texto, word);
      j = j + 1;
    }

    if ((texto != '\0') && (word != '\0')) {
        for (i = 0; i < l1; i++) {
          ind = (strlen(texto)-1) / j;
          j = j + 1;
        }
        printf("%s\n", texto);

    } else
    {
        printf("Termo não encontrado na frase.\n");
    }

    return 0;
}
  • Why do you have scanf("%s",texto); and gets(texto); ? just having the gets(texto); With the scanf reading the text, it will only read as far as space exists, i.e., read only the first word of the text. Use gets

  • @Ianmoone - the recommended is to use fgets, not gets, which is very easy to give problems because it can overwrite the memory outside the reading area.

  • I edited the code to put spaces, it makes it easier to read...in the "real world" nobody uses the type of C code that appears here in the OS, all glued and without spaces...another problem of this code (and the absolute majority of C codes that appears here) is the absolute absence of comments explaining the code...who can’t explain in the code what’s going on, so generally you don’t know what’s going on...

2 answers

1

There are several problems in your code and things you are not using, but before you indicate them, I start by presenting a solution following more or less your logic:

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

int main() {
    char texto[200], word[10];
    //ambas as leituras com scanf
    scanf("%199[^\n]", texto);
    scanf("%9s", word);

    int i, presente = 0, tam = strlen(word);
    for(i = 0; texto[i] != '\0'; i++) { //percorre cada letra do texto
        if (memcmp(&texto[i], word, tam) == 0){ //testa se na letra em que vai existe a palavra
            presente = 1; 
            //loop para remover a palavra do texto
            for (; texto[i] != '\0'; i++){ 
                texto[i] = texto[i + tam];
            }
            break;
        }
    }

    if (presente) {
        printf("%s\n",texto);
    } else {
        printf("Termo não encontrado na frase.\n");
    }

    return 0;
}

Watch it work on Ideone

To test the existence of the word from a certain letter I used the function memcmp, comparing memory blocks and indicating how many bytes should be compared.

Now back to your solution. The readings are not good:

scanf("%s",texto);
gets(texto);
scanf("%s",word);

Twice read the texto and is putting together scanf with gets which is to invite disaster. Avoid doing this to the maximum, preferably by not using at all the gets that was deprecated (marked as obsolete) in C++.

There are several variables you are not using, such as the r:

for(i=0;i<l1;i++){
    r=strcmp(texto,word);
    j=j+1;
}

In this for you compare the text with the word and save the result in r, but does not use it. Also the result will always be the same because you compare the whole text and not just from a specific letter. In addition the end of the loop is done with i < l1, but l1 was not even initialized.

Later he used it too tam=strlen(texto); but has no use in the rest of the program.

  • "%S9" -> "%9s" etc

  • @zentrunix thanks :), was even inattention

  • also: "%[ n]199"

  • @zentrunix I’m sorry, I don’t do a post on the site with this because I know it’s no reason to create a post, however I would like to be clarified a question. What is [ n] for? what is the difference between scanf("%s[^\n]");and scanf("%s");?

  • @That’s for reading to the end of the line, because the scanf("%s") read only one word. No need to make a post, can ask here because I put this in my reply

  • Ah ok, I get it. Thank you very much for the explanation.

Show 1 more comment

0


You can use the functions strstr() and memmove(), both from the standard library string.h.

The function strstr() can be used to search for the term within the sentence and the function memmove() to remove the term, see only:

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

int main( void )
{
    char * posicao = NULL;
    char frase[200];
    char termo[200];

    printf("Digite a frase: ");
    scanf( "%[^\n]%*c", frase );

    printf("Digite o termo: ");
    scanf( "%[^\n]%*c", termo );

    /* Procura e recupera posicao do termo na frase */
    posicao = strstr( frase, termo );

    /* verifica se o termo foi encontrado */
    if( posicao == NULL )
    {
        printf("Termo não encontrado na frase.\n");
        return 1;
    }

    /* Remove o termo da frase */
    memmove( posicao, posicao + strlen(termo), strlen(posicao) - strlen(termo) + 1 );

    /* Exibe frase modificada */
    printf("Frase modificada: %s\n", frase );

    return 0;
}

Testing:

Digite a frase: O rato roeu a roupa do rei de roma.
Digite o termo: roupa
Frase modificada: O rato roeu a  do rei de roma.
  • did not know about some predefined functions in the string library, so I tried to perform the force.

Browser other questions tagged

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