PE2 (AY24/25)
Problems
2. Thesis
A classic string manipulation problem.
My solution is to insert the \n
at the proper white space to make sure we've excluded the leading and trailing spaces.
The idea is that, i
represents the starting character of a word of a white space, one_ahead_len
stores the length of the current line plus one word or white space . And every time, we first get the next word length, which will return 1) 1 if line[i]
is a space 2) the length of the word if it is the start of a word. It is implemented as follows:
Let's continue, if the curr_len
is bigger than limit
, then we need to wrap by replacing the white space character with \n
character. Now, let's see Line 12 to Line 19, this indicates that there are two cases when we wrap the line, it is 1) either you are at the start of a word 2) or you are at the start of a white space. In the first case, we should replace the white space which is exactly one position before i
(line[i-1]
) with \n
while in the second case, we should replace the line[i]
with \n
and increment i
by 1 to let it point to the next starting position of a word.
After we have done setting our \n
, we set one_ahead_len = 0
and skip the increment of i += next_length
because we haven't started dealing with the word starting at i
.
In the normal case where one_ahead_line <= limit
, we don't need to do anything and just need to set i += next_length
Tips
When doing string traversal using while loop, always add current character is not equal to
\0
as one of its terminating condition!
Last updated