Replace a string character with an asterisk

Asked

Viewed 10,434 times

0

The question is as follows: Make a program that reads a text (string) typed by the user with a maximum of 500 characters. Print this text by replacing the first letter of each word with an asterisk '*'.

Read the 500 characters I managed to do:

printf("Digite uma palavra (tamanho maximo de 500 letras):");
gets(palavra);

I’m having a hard time understanding what to do. I need palavra[i]!='\0'

If you use the for would look something like this?

for (i=0; palavra[i]!='\0' ; i++ )
{
    for (i=0 ; palavra[i]<'\0'; i++ )
    { 
        while (palavra[i]==palavra[i+1])
        {
           palavra[i]=' ';
           achou=1;
           printf ("%c\n\n", palavra[i]);
           i++;
        }
    }
}
  • 1

    Don’t use gets(). It is impossible to use this function safely and there is another very similar function that you can replace: fgets(). Also, the function you use is not part of the definition of the C language in the last published version (existed in C99, was removed in C11).

1 answer

1

To iterate over a string in C is usually done like this:

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

int main() {
    char s[128];
    gets(s);
    for (int i = 0; i < strlen(s); ++i) {
        printf("%c", s[i]);
    }

    return 0;
}

What you wrote does more or less the same thing, but you don’t need the for within the first for.

Now, usually a word and a set of characters between spaces. So every time you see a space Voce you can swap the following letter for a '*'. Something like:

if (s[i] == ' ') {
    s[i + 1] = '*';
}

Clearly, taking care to see if the string does not end with a space.

  • Cool the answer, but I would add in if the test s[i + 1] != '\0' also, to be complete, instead of just warning.

  • Thank you very much, guys!

  • Thank you guys! It helped me a lot! The first letter also needed to be replaced by the asterisk, so I put word[1]='*'.

  • @Karla the first letter and palavra[0], take care.

  • That’s right, thank you!

Browser other questions tagged

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