在字符串列表中添加空格? [英] Adding a whitespace inside a List of strings?

查看:78
本文介绍了在字符串列表中添加空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例输入:Hi,你好吗?,结果:Hi,", ;,是",""、"你?

public void getCipher(ArrayList list) {字符串正则表达式 = "\", \";"+ "\", ";+ "\"";for(字符串输入:列表){字符串 newResult = 输入 + 正则表达式;System.out.print(newResult);}}

解决方案

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

public List更新字符串(列表<字符串>列表){字符串正则表达式 = "\", \";"+ "\", ";+ "\"";for (int i = 0; i < list.size(); i++) {list.set(i, list.get(i) + regex);}退货清单;}

I have an ArrayList of strings which contains different words. What I am trying to do is to add whitespace inside the list between each word.

My code does print out the elements with whitespace, but as printout only, I need the whitespace to be included in the list so I can use it as a value.

Example input: Hi, how are you?, result: Hi,", " ", "are", " ", "you?

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

解决方案

Iterate the list and update each string in it with the new string as shown below:

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

Output:

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

这篇关于在字符串列表中添加空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆