我正在尝试将具有最大允许字符的Last空格的String拆分:
期望:
String name =" John David Guetta MarkHenry Anthoney Sam";
允许的最大字符数: 30
所以它应该返回:
John David Guetta MarkHenry
Anthoney Sam
实际结果:
John David Guetta MarkHenry An
thoney Sam
代码:
public static List<String> splitByLength(String str, int n) {
List<String> returnList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (i > 0 && (i % n == 0)) {
returnList.add(sb.toString());
sb = new StringBuilder();
}
sb.append(str.charAt(i));
}
if (StringUtils.isNoneBlank(sb.toString())) {
returnList.add(sb.toString());
}
return returnList;
}
答案 0 :(得分:0)
您可以使用最多可接受30个字符的正则表达式:
String name = "John David Guetta MarkHenry Anthoney Sam";
Pattern p = Pattern.compile(".{1,30}(\\s+|$)");
Matcher m = p.matcher(name);
while(m.find()) {
System.out.println(m.group().trim());
}
注意(\\s|$)
要么在空格上打破要么在初始字符串结束时打破。
答案 1 :(得分:0)
我总是发现使用正则表达式很困难和麻烦,所以这里有一个我会用的解决方案
private static void splitByLength(String str, int n) {
String newStr = "";
int splitIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ' ') {
newStr = newStr + str.charAt(i); //Keep adding chars until you find a space
if (newStr.length() > n) { //If newStr's length exceeds 'n', break the loop
break;
}
} else {
splitIndex = i; //Store the last space index
newStr = newStr + ' ';
}
}
System.out.println(str.substring(0, splitIndex).trim()); //Use the splitIndex to print a substring
System.out.println(str.substring(splitIndex, str.length()).trim());
}