3 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以嘗試string使用兩個(gè)索引遍歷輸入beginIndex,endIndex并在執(zhí)行過(guò)程substrings中從輸入string中獲?。?/p>
public static List<String> descriptionFormatter(String str, int amt) {
List<String> result = new ArrayList<>();
// trim the input string to avoid empty strings at the end
str = str.trim();
int beginIndex = 0;
int endIndex = amt;
final int length = str.length();
while(endIndex < length) {
// if we landed on something other than space
// increase the end index for the substring
// until we hit a space
while(endIndex < length && str.charAt(endIndex) != ' ') {
++endIndex;
}
result.add(str.substring(beginIndex, endIndex).trim());
beginIndex = endIndex;
endIndex += amt;
}
// Add the last string if any left
if(beginIndex < length) {
result.add(str.substring(beginIndex).trim());
}
return result;
}
public static void main(String[] args) {
String str = "hello world apple orange grapes juice spagehtti sauce milk";
descriptionFormatter(str, 34).forEach(System.out::println);
}
輸出:
hello world apple orange grapes juice
spagehtti sauce milk

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
public static List<String> descriptionFormatter(String string, int amt) {
List<String> stringPieces = new ArrayList<>();
StringBuilder strOfMaxLen = new StringBuilder();
StringBuilder strExceedsMaxLen = new StringBuilder();
String[] splitted = string.split(" ");
for (int i = 0 ; i < splitted.length; i++) {
String piece = splitted[i];
int pieceLen = piece.length();
if (strOfMaxLen.length()+pieceLen < amt) {
if (strOfMaxLen.length() != 0) {
strOfMaxLen.append(" ");
}
strOfMaxLen.append(piece);
} else {
if (strExceedsMaxLen.length() != 0) {
strExceedsMaxLen.append(" ");
}
strExceedsMaxLen.append(piece);
}
}
stringPieces.add(strOfMaxLen.toString());
stringPieces.add(strExceedsMaxLen.toString());
return stringPieces;
}

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
嘗試這樣做
static List<String> split(String s, int size) {
return split(s.toCharArray(), size);
}
static List<String> split(char[] s, int size) {
List<String> strs = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length; ++i) {
if (i % size == 0) {
if(s[i] == ' ') {
strs.add(sb.toString());
sb = new StringBuilder();
}else {
StringBuilder newStringBuilder = new StringBuilder();
int length = sb.length();
while (length > 0 && sb.charAt(length - 1) != ' ') {
newStringBuilder.insert(0, sb.charAt(length - 1));
sb.deleteCharAt(length - 1);
--length;
}
if(sb.length() > 0) strs.add(sb.toString());
sb = newStringBuilder;
}
}
sb.append(s[i]);
}
if (sb.length() > 0) {
strs.add(sb.toString());
}
return strs;
}
添加回答
舉報(bào)