String Helper Methods (Java 11)
Problem
Read one line. Print four lines: blank: true or false (true if the line has only white space), stripped: [text without spaces at both ends], repeated: the stripped text three times joined with - (empty when blank), and words: the number of words.
Constraints
- 0 <= length <= 1000
Examples
Input
hello world
Output
blank: false stripped: [hello world] repeated: hello world-hello world-hello world words: 2
Solutions
Before Java 11 you needed trim, length checks and loops for these tasks. trim only removes characters up to the space code, while Java 11 strip also removes Unicode spaces.
/*
* Problem : Process one line of text.
* Input : One line of text.
* Output : Four text facts.
* Approach: Use string methods.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String s) {
// Step 1: Before Java 11 we used trim() and checked the length by hand.
String stripped = s.trim();
boolean blank = stripped.length() == 0;
// Step 2: Repeat the text 3 times with "-" between. Java 8 has no String.repeat, so we use a loop.
StringBuilder repeated = new StringBuilder();
for (int i = 0; i < 3 && !blank; i++) {
if (i > 0) {
repeated.append("-");
}
repeated.append(stripped);
}
// Step 3: Count the words.
int words = blank ? 0 : stripped.split("\\s+").length;
return new String[] {"blank: " + blank, "stripped: [" + stripped + "]", "repeated: " + repeated, "words: " + words};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(String.join("\n", solve(s)));
}
}
Hints (1)
- How do you repeat a string in Java 8?