Home>

I would like to create a program that becomes "ab * cd * ed * gh * ij *" by replacing the multiple 3 character with "*" when entering "abcdef ghijk" using an array, for example. I can't think of a way to change the multiple of 3 to "*", so please help me.
The program I actually wrote is as follows, but it is still incomplete, so I would like to help with the information written in the for statement.

include define NUM 10000

int main (void)
{
char str [NUM];
int i, j;

printf ("Enter a string. \ N");
scanf ("% s", str);

for (i = 0;str [i]! ='\ 0';i ++) {

}

return 0;
}

  • Answer # 1

    A multiple of 3 means that the remainder is 0 when divided by 3.
    In the case of 3, 6 and 9, if you divide it by 3, the remainder will be 0.
    Since i starts from 0, set * when i is 2,5,8.
    Judgment that i is 2,5,8 can be judged by whether (i + 1)% 3 is 0.
    (Or whether i% 3 is 2 or not)

    #include<stdio.h>
    #define NUM 10000
    int main (void)
    {
        char str [NUM];
        int i, j;
        printf ("Enter a string. \ N");
        scanf ("% s", str);
        for (i = 0;str [i]! ='\ 0';i ++) {
            if ((i + 1)% 3 == 0) {
                str [i] ='*';
            }
        }
        printf ("% s \ n", str);
        return 0;
    }


    Below, the execution result
    Please enter a character string.
    abcdefghij
    ab * de * gh * j

    When presenting the source, do not paste it as it is.
    Click thebutton.
    Then
    ‘" Enter the language here
    code
    ‘’ ‘
    Because the character of
    ‘’ C

    ‘’ ‘
    C in the "Enter language here" section
    Please paste the source in the place of ①.
    This will give you a nicely organized source of indentation.
    You can edit this question itself, so please do so.

  • Answer # 2

    All you have to do is substitute the * character when i is a multiple of 3.
    Good luck and try to write the code

  • Answer # 3

    Isn't it just too difficult to think about?

    For example
    What to do if you are given a piece of paper with a character string and are told to "paint all the characters that are multiples of 3 in black"? Why don't you think about it?

    While counting the number of characters from the beginning
    "1,2,3 (blacken here), 1,2,3 (blacken here), 1,2,3 (blacken here), ..."
    Isn't it working like that?

    int main (void)
    {
        char Str [] = "abcdefghij";// Given a string
        char * p;
        unsigned char counter = 0;
        for (p = Str;* p! ='\ 0';++ p)
        {
            ++ counter;// Count as 1,2,3, ...
            when (count == 3) // 3
            {
                * p ='*';// Replace characters with'*'
                counter = 0;// Next count from 1 again
            }
        }
        printf ("% s \ n", Str);
        return 0;
    }