Java 在奇数位置的列表元素之间添加空格
我有一个字符串:Java 在奇数位置的列表元素之间添加空格,java,Java,我有一个字符串: str=“你好” 我正在删除空白: String[]parts=str.split(\\s+) 创建列表并用零件填充它: List<String> theParts = new ArrayList<String>(); for (int i = 0; i < parts.length; i++) { theParts.add(parts[i]); } 然后,我想更改部分列表,以便在各部分之间包含一个空格(表
str=“你好”
我正在删除空白:
String[]parts=str.split(\\s+)代码>
创建列表并用零件填充它:
List<String> theParts = new ArrayList<String>();
for (int i = 0; i < parts.length; i++) {
theParts.add(parts[i]);
}
然后,我想更改部分
列表,以便在各部分之间包含一个空格(表示其他列表大多少的数字)
因此,我希望部分成为(在每个奇数位置添加一个空格):
我不确定列表是否会出现这种情况,但我想不出其他解决方案
或者使用类似join的方法(不起作用,只是使用类似的方法的想法):
if(otherList.size()>theParts.size()){
对于(int i=0;i
填充列表时只需插入空格即可:
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]);
}
List theParts=newarraylist(2*parts.length-1);
对于(int i=0;i0)部分加上(“”);
第三部分增加(第[i]部分);
}
您可以使用分词
正则表达式:
public void test() throws Exception {
String str = "Hello there";
List<String> strings = Arrays.asList(str.split("\\b"));
for ( String s : strings ) {
System.out.println("'"+s+"'");
}
}
public void test()引发异常{
String str=“你好”;
列表字符串=数组.asList(str.split(\\b”);
用于(字符串s:字符串){
System.out.println(““+s+””);
}
}
这将为您保留所有空间
“你好”
''
“有”
为什么不能在添加部分的每个成员后添加一个仅包含空格的字符串
<代码>零件添加(零件[i]);第三部分加上(“”)那么,你基本上添加了你所使用的空白空间吗?为什么你试图在列表中间插入这个空间,而不是把另一个元素推到最后呢?或者,既然您已经知道另一个列表的长度,为什么不创建一个该大小的列表,并将拆分字符串中的项目插入到该列表中,或者使用空格?当另一个列表的大小超过部分大小的两倍时,会发生什么情况?我应该在末尾加上更多的空格吗?好的,谢谢!我还可以使用List theParts=newarraylist(otherList.size())代码>欢迎使用堆栈溢出!感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。通过说明为什么这是一个很好的问题解决方案来正确解释它的长期价值,并将使它对未来有其他类似问题的读者更有用。请在你的回答中添加一些解释,包括你所做的假设。好的。。。我会在下次你可以立即-无需等到“下一次”。
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]);
}
public void test() throws Exception {
String str = "Hello there";
List<String> strings = Arrays.asList(str.split("\\b"));
for ( String s : strings ) {
System.out.println("'"+s+"'");
}
}
for(String dis : theParts){
newParts.add(dis);//'newPart is another list '
String last = parts[parts.length -2]; // until new list read last element
if(!last.equals(dis)){
newParts.add(" ");
}if(last.equals(dis)){
newParts.add(" ");
}
}