繁体   English   中英

在每 n 个字符后拆分一个字符串,忽略 java 中的空格,将其存储在 arraylist 中

[英]Split a String after every n characters ignoring whitespaces in java store it in arraylist

我有一个字符串,我想在每 n 个字符之后拆分并将其存储在字符串数组中,但这应该忽略所有空格。

例如我有一个字符串如下,

String str = "这是一个字符串,每10个字符需要拆分一次";

output 应该是,

["This is a Str", "ing which nee", "ds to be split", "ted after ev", "ery 10 chara", "cters"]

(编辑)--> 我正在使用下面的 function。 如何将其存储在字符串数组中。

如 output 所示,它忽略了所有空格的索引。 java有什么办法吗?

public static String test(int cnt, String string) {
        AtomicInteger n = new AtomicInteger(cnt);
        return string
                .chars()
                .boxed()
                .peek(value -> {
                    if (!Character.isWhitespace(value)) {
                        n.decrementAndGet();
                    }
                })
                .takeWhile(value -> n.get() >= 0)
                .map(Character::toString)
                .collect(Collectors.joining());

我使用了一种标准方法来循环遍历字符串并计算字符数:

public static void main(String[] args) throws ParseException {
    String str = "This is a String which needs to be splitted after every 10 characters";
    System.out.println(split(str, 10));
}

public static List<String> split(String string, int splitAfter) {
    List<String> result = new ArrayList<String>();
    int startIndex = 0;
    int charCount = 0;
    for (int i = 0; i < string.length(); i++) {
        if (charCount == splitAfter) {
            result.add(string.substring(startIndex, i));
            startIndex = i;
            charCount = 0;
        }
        // only count non-whitespace characters
        if (string.charAt(i) != ' ') {
            charCount++;
        }
    }
    // check if startIndex is less than string length -> if yes, then last element wont be 10 characters long
    if (startIndex < string.length()) {
        result.add(string.substring(startIndex));
    }
    return result;
}

结果与您发布的结果略有不同,但从您的预期结果来看,它与描述并不完全相符:

[This is a Str, ing which ne, eds to be spl, itted after,  every 10 cha, racters]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM