Challenge:
Write a program that will clean up the words from extra numbers and symbols.
Specifications:
The first argument is a path to a file.
Each line includes a test case with a list of words: letters are both lowercase and uppercase, and are mixed with extra symbols.
Print the words separated by spaces in lowercase letters.
The length of a test case together with extra symbols can be in a range from 10 to 100 symbols. The number of test cases is 40.
Solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CleanWords {
public static void main(String[] args) {
try (Scanner input = new Scanner(new File(args[0]))) {
while(input.hasNextLine()) {
System.out.println(sanitize(input.nextLine()));
}
} catch (FileNotFoundException fnfe) {
System.out.println(args[0] + " doesn't exist");
}
}
private static String sanitize(String input) {
StringBuilder result = new StringBuilder();
for (String s : input.split("[^a-zA-Z]+")) {
result.append(' ').append(s);
}
return result.toString().toLowerCase().trim();
}
}
Sample Input:
(--9Hello----World...--) Can 0$9 ---you~ 13What213are;11you-123+138doing7
Sample Output:
hello world can you what are you doing
I'm wondering if:
- It would be more efficient to call
trim
within the loop? - If there's a less costly way than looping twice between calling both
toLowerCase
andtrim
These may seem like givens, but it's been a long time since I did one of these, and I wanted to get back into it with a seemingly simple one. I passed on the first try which I largely have CR to thank for. For those interested, the source is CodeEval.com.