patternjavaMinor
CodeEval Challenge: Remove specified characters from a string
Viewed 0 times
codeevalchallengeremovecharactersfromstringspecified
Problem
Question
Write a program which removes specific characters from a string.
The first argument is a path to a file. The file contains the source
strings and the characters that need to be scrubbed. Each source
string and characters you need to scrub are delimited by comma.
Input sample:
how are you, abc
hello world, def
Output sample:
how re you
hllo worl
I have used regex to eliminate the characters.
The above code passes all the test cases.
Is this the most optimized code or can it be improved further?
Write a program which removes specific characters from a string.
The first argument is a path to a file. The file contains the source
strings and the characters that need to be scrubbed. Each source
string and characters you need to scrub are delimited by comma.
Input sample:
how are you, abc
hello world, def
Output sample:
how re you
hllo worl
I have used regex to eliminate the characters.
public class Main{
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader br = new BufferedReader(new FileReader(file));
String s;
while ((s = br.readLine()) != null) {
s = s.trim();
String arr[]=s.split(",\\s");
String pat="([^"+arr[1]+"])";
Pattern p=Pattern.compile(pat);
Matcher m=p.matcher(arr[0]);
while(m.find())
{
System.out.print(m.group(0));
}
System.out.println();
}
br.close();
}
}The above code passes all the test cases.
Is this the most optimized code or can it be improved further?
Solution
You can extract out the requirement into its own method:
And since you have to split from a single
If you are on Java 8, you can use a combination of
private static String removeCharacters(String input, String excludedLetters) {
// ...
}And since you have to split from a single
String first, you can use a wrapper method in addition to the one above:private static String removeCharacters(String line) {
String[] parts = // ...
return removeCharacters(parts[0], parts[1]);
}If you are on Java 8, you can use a combination of
try-with-resources and Files.lines() to Streamline the processing (pun intended):try (Stream lines = Files.lines(Paths.get(/* ... */))) {
lines.map(Main::removeCharacters).forEach(System.out::println);
}Code Snippets
private static String removeCharacters(String input, String excludedLetters) {
// ...
}private static String removeCharacters(String line) {
String[] parts = // ...
return removeCharacters(parts[0], parts[1]);
}try (Stream<String> lines = Files.lines(Paths.get(/* ... */))) {
lines.map(Main::removeCharacters).forEach(System.out::println);
}Context
StackExchange Code Review Q#98323, answer score: 4
Revisions (0)
No revisions yet.