Question
Needs to be in Java, please don't copy random answers for other problems for this solution All methods listed below must be public and static.
- Needs to be in Java, please don't copy random answers for other problems for this solution
- All methods listed below must be public and static.
- If your code is using a loop to modify or create a string, you need to use the StringBuilder class from the API.
- Keep the loops simple but also efficient. Remember that you want each loop to do only one "task" while also avoiding unnecessary traversals of the data.
- No additional methods are needed.
- Important: you must not use either break or continue in your code.
- No other APIs allowed
You are allowed to use the following from the Java API:
- class String
- length
- charAt
- class StringBuilder
- length
- charAt
- append
- toString
- class Character
- any method
- class String
Create a class called HW2 that contains the following methods:
-
nthWord takes an int and a String as input and returns a String: The input int represents a number n that is assumed to be positive, and the output string contains every nth word of the input string, starting with the first word, separated by a single space. {\em For this method, a word is defined to be a sequence of non-space characters.} There should be no space at the end of the output string.
> HW2.nthWord(3, "zero one two three four five six seven") "zero three six"
-
truncateAfter takes an int and a String as input and returns a String: The input string may contain hyphens and spaces that mark appropriate places to truncate the string. The output string will be a truncated version of the input string, and the input int value is the desired length of the output string. The output string should truncate the input string at the first legal spot such that the output string will have at least the desired length. If the truncation happens at a space, the space is not included in the output, but if the truncation happens at a hyphen, the hyphen is included. No other hyphens are included in the output, but the other spaces are. (If the input string does not have enough characters to meet the desired minimum, then the output should be the entire input string without the hyphens.)
> HW2.truncateAfter(5, "La-te-ly the-re.") "Late-" > HW2.truncateAfter(6, "La-te-ly the-re.") "Lately" > HW2.truncateAfter(7, "La-te-ly the-re.") "Lately the-"
-
truncateBefore: the same as the truncateAfter method, but now the input int value is the maximum, and the string should be truncated at the latest possible point such that the resulting string has no more than the desired length.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started