net.dongliu.commons.lang.Strings Maven / Gradle / Ivy
package net.dongliu.commons.lang;
import java.util.Collection;
/**
* string utils methods
*
* @author Dong Liu
*/
public class Strings {
/**
* get sub-string between begin and end.
*
* @param str if null, return null
* @param begin the begin str, cannot be null
* @param end the end str, cannot be null
* @return str between begin and end. if not exists, return null
*/
public static String subStrBetween(String str, String begin, String end) {
if (str == null) {
return null;
}
int idx = str.indexOf(begin);
if (idx < 0) {
return null;
}
idx += begin.length();
int eidx = str.indexOf(end, idx);
if (eidx < 0) {
return null;
}
return str.substring(idx, eidx);
}
/**
* split str by white characters
* "a b c" to ["a", "b", "c"]
* " a c " to ["a","c"]
*/
public String[] split(String str) {
return str.trim().split("\\w+");
}
/**
* join str
*
* @param strings not null
* @return string
*/
public static String join(String... strings) {
StringBuilder sb = new StringBuilder();
for (String string : strings) {
sb.append(string);
}
return sb.toString();
}
/**
* specify a separator, and then can join strings
*
* Strings.separator(",").join("test", "paste")
*
*
* @param separator not null
* @return
*/
public static Join sep(String separator) {
return new Join(separator);
}
/**
* join strings with separator
*
* @param strings not null
* @param separator not null
* @return string not null
*/
public static String join(Collection strings, String separator) {
StringBuilder sb = new StringBuilder();
int total = strings.size();
int i = 0;
for (String str : strings) {
sb.append(str);
if (i++ < total - 1) {
sb.append(separator);
}
}
return sb.toString();
}
public static class Join {
private final String separator;
public Join(String separator) {
this.separator = separator;
}
public String join(String... strings) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
sb.append(strings[i]);
if (i < strings.length - 1) {
sb.append(separator);
}
}
return sb.toString();
}
}
}