Originally Posted by
CproG100
of course.. i know it's a for loop. i just don't how to master the array's index to creat what they want. if for example we have this sentence: "i am you friend".. it will be : ia my ourf riend.
Do the exercise with paper and pencil a few times. Note the patterns as they become evident to you, after a few repetitions of it.
Those patterns, when simplified into small steps, will become the backbone of your logic for the program.
Code:
for each char in the string, starting with the last (rightmost) char
move every char, one index to the right, including the end of string
char: '\0', which you can't see when you print the string.
if the char is a space, move the next char after the space, to
the right, one index. Then insert a space.
end for
Which should be OK, BUT it will be one one index over to the right, from where it should be:
Code:
Ia myou rfriend is the final goal, but
Ia myou rfriend is what you'll wind up with
Note that it's one space too long, on the right hand side, and the first char on the left, is a space - which needs to be removed.
Fortunately, you have a function to remove leading spaces from the left hand side of strings. So use it, here
Perfect?
I haven't coded this up, so work it through, and code it up, and test it. It should be very close. Note that you will need one extra index number (length of the char array), to do this. In C, every group of letters or numbers, that is a string, MUST have an end of string char as it's rightmost char, to mark the end of the string. Any group of letters or numbers that DOES NOT have an end of string char at the end of it, is just a bunch of char's -- NOT a string.
Note that the end of string char ('\0'), can also be a 0, but it can't be a '0', because a '0' is a zero char.