Intention is to take a current line (String that contains commas), replace white space with "" (Trim space) and finally store split String elements into the array.
Why does not this work?
String[] textLine = currentInputLine.replace("\\s", "").split(",");
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
The String
class has the following methods:
String replace(char oldChar, char newChar)
String replace(CharSequence target, CharSequence replacement)
boolean startsWith(String prefix)
boolean endsWith(String suffix)
boolean contains(CharSequence s)
String replaceAll(String regex, String replacement)
String replaceFirst(String regex, String replacement)
String[] split(String regex)
boolean matches(String regex)
So here we see the immediate cause of your problem: you're using a regex pattern in a non-regex method. Instead of replace
, you want to use replaceAll
.
Other common pitfalls include:
split(".")
(when a literal period is meant)matches("pattern")
is a whole-string match!
contains("pattern")
; use matches(".*pattern.*")
insteadSplitter
Depending on your need, String.replaceAll
and split
combo may do the job adequately. A more specialized tool for this purpose, however, is Splitter
from Guava.
Here's an example to show the difference:
public static void main(String[] args) {
String text = " one, two, , five (three sir!) ";
dump(text.replaceAll("\\s", "").split(","));
// prints "[one] [two] [] [five(threesir!)] "
dump(Splitter.on(",").trimResults().omitEmptyStrings().split(text));
// prints "[one] [two] [five (three sir!)] "
}
static void dump(String... ss) {
dump(Arrays.asList(ss));
}
static void dump(Iterable<String> ss) {
for (String s : ss) {
System.out.printf("[%s] ", s);
}
System.out.println();
}
Note that String.split
can not omit empty strings in the beginning/middle of the returned array. It can omit trailing empty strings only. Also note that replaceAll
may "trim" spaces excessively. You can make the regex more complicated, so that it only trims around the delimiter, but the Splitter
solution is definitely more readable and simpler to use.
Guava also has (among many other wonderful things) a very convenient Joiner
.
System.out.println(
Joiner.on("... ").skipNulls().join("Oh", "My", null, "God")
);
// prints "Oh... My... God"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With