public String split(String regex)
public String split(String regex, int limit)
regex : 应用于字符串的正则表达式。
limit :数组中字符串的数量限制。如果它为零,它将返回所有匹配正则表达式的字符串。
返回值:array of strings
limit = 0:这将排除尾随的空字符串;
limit > 0,因此 split 方法仅返回 limit 个子字符串;
limit < 0,它会在输出中包含尾随的空字符串。
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> res = new ArrayList();
for (String s : words) {
int n = s.length(), left = 0;
for (int i = 0; i <= n; i++) {
char c = i < n ? s.charAt(i) : separator;
if (c == separator) {
String t = s.substring(left, i);
left = i + 1;
if (t != "") res.add(t);
}
}
}
return res;
}
}
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
String regex = "\\" + String.valueOf(separator);
List<String> res = new ArrayList<>();
for (String w : words){
String[] ws = w.split(regex);
for (String s : ws){
if (s != null && s.length() >= 1) res.add(s);
}
}
return res;
}
}