AP CSA Practice Free Response Question 1
A company needs to format words for display on a website. The rules for formatting are:
- If a word contains more than one occurrence of any vowel ('a', 'e', 'i', 'o', 'u', case sensitive), replace each occurrence after the first with an asterisk (*).
- Trim any white spaces from the beginning and end of the string.
- If the resulting word does not ends with a vowel, append an exclamation mark (!) to the end.
Part a.
Write the method formatWord
that takes a String
parameter word
and returns the formatted string as per the rules above.
Examples:
Input |
Output |
"eager" |
"eag*r!" |
" outcome " |
"outc*me" |
"apple" |
"apple" |
"ChatBot" |
"ChatBot!" |
AP CSA Practice Free Response Question 2
Write a class SentenceAnalyzer
that analyzes a sentence (a String consisting of words separated by single spaces, with no punctuation). The class has the following methods:
public static int countWord(String sentence, String word)
- to be answered in part a.
public static String swapFirstLast(String sentence)
- to be answered in part b.
Part a: countWord Method
Write a static method countWord
that takes two parameters: a String sentence
and a String word
. The method returns the number of times word
appears in the sentence
. Two words will not match if there are case discrepancies.
Example:
countWord("java is fun and java is powerful", "java")
returns 2
countWord("Test test TEST", "test")
returns 1
Part b: swapFirstLast Method
Write a static method swapFirstLast
that takes a String sentence
and returns a new String
in which the first and last words have been swapped. Spaces between words must be preserved, and words are separated by a single space. If there is only one word, return the original sentence.
Examples:
swapFirstLast("coding is creative")
returns "creative is coding"
swapFirstLast("hello")
returns "hello"