Homework: String – Words and Separators


This homework is necessary preparation for the lab. Make sure you type your answers in a file you bring to the lab so that you will be able to quickly copy and paste them into the file provided in the lab.

  1. Implement the static method generateElements declared as follows:

    Informally, generateElements extracts the characters from the given String and puts them in the given Set. Note that there is no requires clause to rule out repeated characters in str and that charSet is a replaces-mode parameter.

  2. Implement the static method nextWordOrSeparator declared as follows:

    A "word" is defined as a string of characters that are not in the separators set, and a "separator string" instead is defined as a string of characters that are in the separators set. nextWordOrSeparator is expected to return the longest word or separator string that starts at the given position in the given String.

    Informally, the ensures clause states that if the character at the given position in text is not in the set of separators (lines 20-21)—that is, we are extracting a word—then the String returned by nextWordOrSeparator must be the substring of text that starts at the given position (lines 18-19), is made up entirely of characters not in the set of separators (line 22), and it is either at the end of text (line 23) or it is followed in text by a character that is in the set of separators (lines 24-25). On the other hand, if the character at the given position in text is in the set of separators (lines 20 and 26)—that is, we are extracting a separator string—then the String returned by nextWordOrSeparator must be the substring of text that starts at the given position (lines 18-19), is made up entirely of characters in the set of separators (line 27), and it is either at the end of text (line 28) or it is followed in text by a character that is not in the set of separators (lines 29-30).