R
R
Retr0Hacker2021-11-28 00:58:33
C++ / C#
Retr0Hacker, 2021-11-28 00:58:33

How to remove words from a sentence that do not contain the specified letter?

Good evening everyone! A new task has appeared:
"Enter a sentence from the keyboard. Delete from it all words that do not contain the specified letter."

I can’t change the remove_words function in any way (it removes all words in which there is a specified letter, but it should be the other way around)

Give advice on what and how to change?

Here is my code:

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX_SIZE 100
char* remove_words(char* s, int c);

int main()
{
    char s[MAX_SIZE];
    char c;

    printf("Enter string: ");
    gets_s(s);

    printf("Enter letter: ");
    scanf_s("%c", &c);

    puts(remove_words(s, c));

    return 0;
}

char* remove_words(char* s, int c) {
    int   g;
    char* i, * p, * t = s;
    for (p = s; *s; *s = *p) {
        if (!isspace(*p)) {
            i = p;
            g = 0;
            while (*i && !isspace(*i)) {
                if (*i == c)
                    g = 1;
                ++i;
            }

            if (g)
                p = i;
            else {
                while (p != i)
                    *s++ = *p++;
            }
        }
        else
            ++s, ++p;
    }
    return t;
}


PS
I have already understood what is needed if (*i == c) ==> if (*i != c), and, most likely, redo this section:
if (g)
                p = i;
            else {
                while (p != i)
                    *s++ = *p++;
            }
        }
        else
            ++s, ++p;
    }
    return t;

But no matter what I try, nothing helps!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-28
@wataru

If you used normal variable names, then it would immediately become obvious to you which one line (even one character!) You need to change to remove words without a letter, instead of words with letters.
Think about what is stored in the variable g - what does it mean, what is its physical meaning, what values ​​\u200b\u200band under what conditions does it take?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question