我有一个字符串:
str = "你好"
我正在删除空格:
String[] parts = str.split("\\s+");
创建一个列表并用各个部分填充它:
List<String> theParts = new ArrayList<String>();
for (int i = 0; i < parts.length; i++) {
theParts.add(parts[i]);
}
列表的大小是 2。现在,我想增加它的大小,以便与另一个列表的大小相同。
假设另一个列表的大小为 3。 所以,我检查:
if (otherList.size() > theParts.size()) {
然后,我想更改 theParts
列表,以便在其各部分之间包含一个空白空间(该数字显示 otherList 的大小)。
所以,我希望 theParts
为(在每个奇数位置添加一个空格):
theParts[0] = "Hello"
theParts[1] = " "
theParts[2] = "there"
我不确定列表是否会发生这种情况,但我想不出其他解决方案。
或者使用诸如 join 之类的东西(不起作用,只是使用这样的东西的想法):
if (otherList.size() > theParts.size()) {
for (int i = 0; i < otherList.size(); i++) {
if (i%2 !=0) {
String.join(" ", theParts);
}
}
}
最佳答案
只需在填充列表时插入空格即可:
List<String> theParts = new ArrayList<>(2 * parts.length - 1);
for (int i = 0; i < parts.length; i++) {
if (i > 0) theParts.add(" ");
theParts.add(parts[i]);
}
关于java - 在奇数位置的列表元素之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323654/