【问题标题】:Java Split string into array, by size and only split after delimitersJava将字符串按大小拆分为数组,仅在分隔符后拆分
【发布时间】:2014-09-25 07:02:58
【问题描述】:

我有很多字符串,它们的大小实际上是随机的,例如:5 个字符到 12000 个随机字符。

例如:

String 1 : A,b,C,d
String 2 :23,343,342,4535,4535,453,234,
String 3 : ,asdsfdfdasgfdsfsf,dsfdsfdsfdsfsdfdf,sdsfdsfdsfsdf, <- and this around another 1000 times.

我想通过他们的 ID 将他们上传到我的数据库。所以我的问题是 oracle 数据库 varchar 只能包含 4k 字节。

编辑: 所以如果字符串大于4k。我想要一个 String[],其中每个元素最多 4000k 个字符让计数为 3900。(如果我遍历数组,我会返回相同的字符串,并且每个数组元素最后一个“单词”是一个未切片的整个单词)

所以我的想法很简单,如果 string.lenth

到目前为止我的解决方案(没有昏迷护理)

        for (My_type type: types) {
        String[] tokens =
                Iterables.toArray(
                    Splitter
                        .fixedLength(4000)
                        .split(type.area),
                    String.class
                );

如何替换此函数以获得“好数组”?

【问题讨论】:

  • 你能解释一下'否则将它分成大约 4000 只股票'。
  • 只是检查:您的字面意思是“在逗号之后” - 即您是否希望将逗号保留在节的末尾?

标签: java arrays string string-split


【解决方案1】:

我不认为split() 是一个选项。我认为您需要使用 Matcher 来消耗尽可能多的输入,然后构建捕获部分的列表:

Matcher matcher = Pattern.compile(".{1,3999}(,|.$)").matcher(input);
List<String> list = new ArrayList<>();
while (matcher.find())
    list.add(matcher.group());

如果你真的想要一个数组(不推荐)

String[] array = list.toArray(new String[list.size()]);

这个正则表达式是贪婪的,最多会消耗 4000 个以逗号或输入结尾结尾的字符。长度为 3999 用于允许逗号本身多 1,结束标记 $ 之前的点要多消耗 1,因为 $ 是零宽度。

【讨论】:

  • 谢谢,我跳过了数组部分。清单对我有好处。也感谢您的建议。
【解决方案2】:

这会给你这样的令牌,在一个列表中 - 希望没问题。

for (My_type type: types) {
    String longString = type.area;
    List<String> tokens = new ArrayList<>();
    while (longString.length() > 4000) {
        int splitIndex = longString.lastIndexOf(",", 3999);
        if (splitIndex < 0) {
            // no comma found
            throw new IllegalStateException("Cannot split string");
        }
        tokens.add(longString.substring(0, splitIndex));
        longString = longString.substring(splitIndex + 1); // leaving out the comma
    }
    if (tokens.size() == 0) {
        tokens.add(longString);
    }
}

【讨论】:

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