在字符串列表中添加空格?

Adding a whitespace inside a List of strings?

我有一个 ArrayList 字符串,其中包含不同的单词。我想要做的是在每个单词之间的列表中添加空格。

我的代码确实打印出带有空格的元素,但仅作为打印输出,我需要将空格包含在列表中,以便我可以将其用作值。

示例输入:Hi, how are you?,结果:Hi,", " ", "are", " ", "you?

public void getCipher(ArrayList<String> list) {
    String regex = "\", \" " + "\", " + "\"";
    for (String input : list) {
        String newResult = input + regex;
        System.out.print(newResult);
    }
}

迭代列表并使用新字符串更新其中的每个字符串,如下所示:

public List<String> updateStrings(List<String> list) {
    String regex = "\", \" " + "\", " + "\"";
    for (int i = 0; i < list.size(); i++) {
        list.set(i, list.get(i) + regex);

    }
    return list;
}

Test it online:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        List<String> list = new ArrayList<>(List.of("Hello", "World"));
        System.out.println(list);
        System.out.println(updateStrings(list));
    }

    static List<String> updateStrings(List<String> list) {
        String regex = "\", \" " + "\", " + "\"";
        for (int i = 0; i < list.size(); i++) {
            list.set(i, list.get(i) + regex);

        }
        return list;
    }
}

输出:

[Hello, World]
[Hello", " ", ", World", " ", "]

要在列表中的其他项目之间添加空格,我会创建一个新列表并遍历“旧”列表,如下所示:

public ArrayList<String> getCipher(ArrayList<String> list) {
    ArrayList<String> result = new ArrayList<>();
    String regex = "\", \" " + "\", "+ "\"";
    for (String input : list) {
        result.add(input + regex);
        result.add(" ");
    }
    return result;
}

您可以将列表设置为此方法的结果,例如

list = getCipher(list)

您可以使用 flatMap 方法在列表中的元素之间插入空格:

public static void main(String[] args) {
    List<String> list = List.of("Hi,", "how", "are", "you?");
    System.out.println(appendSpaces(list));
}
public static List<String> appendSpaces(List<String> list) {
    return list.stream()
            // append a space before each word
            .flatMap(str -> Stream.of(" ", str))
            // skip first space
            .skip(1)
            // return list
            .collect(Collectors.toList());
}

输出:

[Hi,,  , how,  , are,  , you?]

创意截图:


另请参阅:How to add characters in the middle of a word in an arraylist in java?