【问题标题】:adding to a list with special limit添加到具有特殊限制的列表
【发布时间】:2016-04-29 16:40:00
【问题描述】:

考虑以下单词列表: 但我的列表将包含 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);
}

【问题讨论】:

  • 您有问题吗?因为你不小心……
  • @elliot 是的,那么我如何将每 100 个字符的单词添加到名为 secondaryarraylist 的列表中?
  • 您当前的代码以什么方式做到这一点?
  • @ElliottFrisch 当前代码仅获得前 100 个字符的单词,它会停止。我希望它迭代直到结束,并将每 100 个字符的价值放在一个列表中的单独元素中
  • 不清楚您期望的结果是什么。 1) 你想要正好 100 个字符,还是想要尽可能多的单词,不超过 100 个字符? 2) 当您有 100 个字符或总共 SecondarrayList? 2a) 作为(子)列表? 2b)合并到一个字符串? 2c) 与空间分隔符合并? 2d) 别的? --- 请编辑问题以显示预期输出,例如如果限制为 20(因为 100 不会拆分样本输入)。

标签: java string arraylist substring


【解决方案1】:

如果我理解您的问题,那么您可以检查个人 String(s) 的长度是否小于 100 个字符(如果是,则将它们直接添加到第二个数组列表中)。否则,将前 100 个字符添加到第二个数组列表。此外,根据 Java 变量命名约定,第二个数组列表应命名为 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 个字符转换为多个“单词”,那么您的 else 应该看起来像

} 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);
    }
}

【讨论】:

  • 嗨,那么现在每个元素 secondArraylist 是否包含 100 个字符或更少的单词?因为这是需要的
【解决方案2】:
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;
}

免责声明:我没有编译代码并测试过!它可能无法涵盖所有​​极端情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多