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.

void wrap(char *line, long limit)
{
  size_t len = strlen(line);
  long one_ahead_len = 0;
  long next_length = 0;
  for (long i = 0; i < (long)len;)
  {
    next_length = next_word_length(line, i);
    one_ahead_len += next_length;
    if (one_ahead_len > limit)
    {
      if (line[i] != ' ')
      {
        line[i-1] = '\n';
      }
      else
      {
        line[i] = '\n';
        i += 1;
      }
      one_ahead_len = 0;
      continue;
    }
    i += next_length;
  }
  print_line(line);
}

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:

long next_word_length (char *line, long i)
{
  long len = 0;
  if (line[i] == ' ')
  {
    return 1;
  }
  while (line[i] != ' ' && line[i] != 0)
  {
    len += 1;
    i += 1;
  }
  return len;
}

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

  1. When doing string traversal using while loop, always add current character is not equal to \0 as one of its terminating condition!

Last updated