添加到具有特殊限制的列表

时间:2016-01-22 23:19:14

标签: java string arraylist substring

考虑以下单词列表: 但我的名单将包含100,000个单词

small 
donations 
($1 
to 
$5,000) 
are 
particularly 
important 
to 
maintaining 
tax 
exempt 

目前,下面的代码获得前100个字符的单词,并将其放入另一个列表(称为SecondarrayList)。我希望它在列表末尾添加每100个字符(列表中的每个元素都是一个单词)

所以我们只需要 100个字符的单词,这是每次迭代直到最后一个单词。必须超过 100字符限制

int totalSize = 0;
for (String eachString : list) {
    totalSize += eachString.length();
    if (totalSize >= 100)
        break;
    else
      SecondarrayList.add(eachString);
}

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,那么你可以检查个人String(s)的长度是否少于100个字符(如果是这样的话,直接将它们添加到第二个arraylist)。否则,将前100个字符添加到第二个arraylist。此外,通过Java变量命名约定,第二个arraylist应该命名为secondArrayList。像,

List<String> secondArrayList = new ArrayList<>();
for (String eachString : list) {
    if (eachString.length() < 100) { // <-- is it 100 or fewer chars?
        secondArrayList.add(eachString);
    } else { // <-- otherwise, take the first 100 chars.
        secondArrayList.add(eachString.substring(0, 100));
    }
}

如果你真的想把一个输入的每个100个字符分成多个&#34;单词&#34;然后你的其他人应该看起来像

} else {
    // Iterate the word, shrinking by 100 characters...
    while (eachString.length() > 100) {
        secondArrayList.add(eachString.substring(0, 100));
        eachString = eachString.substring(100);
    }
    // Check if there is anything left...
    if (!eachString.isEmpty()) {
        secondArrayList.add(eachString);
    }
}

答案 1 :(得分:0)

StringBuilder strBuilder = new StringBuilder();
int length = 0;

for (String str : list){
    int totalLength = str.length();
    int startPos = 0;
    //if you have strings longer than 100 characters
    //also handles left overs from previous iterations
    while (length+totalLength>=100){
           int actualLength = Math.min(100,totalLength)
           strBuilder.append(str.substring(startPos,startPos+actualLength));
           secondArrayList.add(strBuilder.build());
           strBuilder.setLength(0);
           startPos += actualLength;
           totalLength -= actualLength;
           length = 0;
    }
    //we know it is safe to add remainder as it is
    // or if the new word skipped the while loop we add it completly
    strBuilder.append(str.substring(startPos,startPos+totalLength))
    length += totalLength;
}

免责声明:我没有编译代码并对其进行测试!它可能不包括所有角落的情况。