String utilities
1.Joiner
Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");
2.Splitter
Splitter allows complete control over all this confusing behavior using a reassuringly straightforward fluent pattern.
Splitter.on(',')
.trimResults()
.omitEmptyStrings()
.split("foo,bar,, qux");
Base Factories
| Method | Description | Example |
|---|---|---|
Splitter.on(char) |
Split on occurrences of a specific, individual character. | Splitter.on(';') |
Splitter.on(CharMatcher) |
Split on occurrences of any character in some category. | Splitter.on(CharMatcher.BREAKING_WHITESPACE) Splitter.on(CharMatcher.anyOf(";,.")) |
Splitter.on(String) |
Split on a literal String. | Splitter.on(", ") Splitter.on(Pattern) |
Splitter.onPattern(String) |
Split on a regular expression. | Splitter.onPattern("\r?\n") |
Splitter.fixedLength(int) |
Splits strings into substrings of the specified fixed length. The last piece can be smaller than length, but will never be empty. | Splitter.fixedLength(3) |
Modifiers
| Method | Description | Example |
|---|---|---|
omitEmptyStrings() |
Automatically omits empty strings from the result. | Splitter.on(',').omitEmptyStrings().split("a,,c,d") returns "a", "c", "d" |
trimResults() |
Trims whitespace from the results; equivalent to trimResults(CharMatcher.WHITESPACE). | Splitter.on(',').trimResults().split("a, b, c, d") returns "a", "b", "c", "d" |
trimResults(CharMatcher) |
Trims characters matching the specified CharMatcher from results. | Splitter.on(',').trimResults(CharMatcher.is('')).split("_a ,_b ,c_") returns "a ", "b ", "c". |
limit(int) |
Stops splitting after the specified number of strings have been returned. | Splitter.on(',').limit(3).split("a,b,c,d") returns "a", "b", "c,d" |
3.CharMatcher
Many needs can be satisfied by the provided CharMatcher factory methods:
- any()
- none()
- whitespace()
- breakingWhitespace()
- invisible()
- digit()
- javaLetter()
- javaDigit()
- javaLetterOrDigit()
- javaIsoControl()
- javaLowerCase()
- javaUpperCase()
- ascii()
- singleWidth()
4.Charsets
Charsets provides constant references to the six standard Charset implementations guaranteed to be supported by all Java platform implementations. Use them instead of referring to charsets by their names.
bytes = string.getBytes(Charsets.UTF_8);
Note: If you're using JDK7, you should use the constants in StandardCharsets
5.CaseFormat
| Format | Example |
|---|---|
LOWER_CAMEL |
lowerCamel |
LOWER_HYPHEN |
lower-hyphen |
LOWER_UNDERSCORE |
lower_underscore |
UPPER_CAMEL |
UpperCamel |
UPPER_UNDERSCORE |
UPPER_UNDERSCORE |
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "CONSTANT_NAME")); // returns "constantName"