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

Java 添加到具有特殊限制的列表中,java,string,arraylist,substring,Java,String,Arraylist,Substring,考虑以下单词列表: 但我的单子上会有10万个字 small donations ($1 to $5,000) are particularly important to maintaining tax exempt 当前,下面的代码获取单词的前100个字符,并将其放入另一个列表(称为SecondarrayList)。我希望它每隔100个字符添加一次,直到列表的末尾(列表中的每个元素都是一个单词) 所以我们只需要100个字符的单词,在每次迭代中,直到最后一个单词为止。必须

考虑以下单词列表: 但我的单子上会有10万个字

small 
donations 
($1 
to 
$5,000) 
are 
particularly 
important 
to 
maintaining 
tax 
exempt 
当前,下面的代码获取单词的前100个字符,并将其放入另一个列表(称为SecondarrayList)。我希望它每隔100个字符添加一次,直到列表的末尾(列表中的每个元素都是一个单词)

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


如果我理解您的问题,那么您可以检查单个
字符串的长度是否小于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));
    }
}

免责声明:我没有编译代码并测试它!它可能不包括所有角落的案例。

您有什么问题吗?因为你不小心…@elliot是的,那么我如何将每100个字符的单词添加到名为secondaryarraylist的列表中?你当前的代码以什么方式不这样做?@ElliottFrisch当前代码只获取前100个字符的单词,然后停止。我希望它迭代到最后,并将每100个字符的值放在列表中单独的元素中。不清楚您期望的结果是什么。1) 您是想要100个字符,还是想要尽可能多的单词,但不要超过100个字符?2) 如果总共有100个字符或单词,那么现在每个元素secondArraylist是否包含100个字符或更少的单词?因为这是必须的
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));
    }
}
} 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);
    }
}
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;
}