代码之家  ›  专栏  ›  技术社区  ›  George

在奇数位置的列表元素之间添加空格

  •  0
  • George  · 技术社区  · 7 年前

    我有一根绳子:

    str = "Hello there"

    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 列表,以便在其各部分之间包含一个空格(该数字表示另一个列表的大小)。

    部分 to be(在每个奇数位置添加空格):

    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);
          }
        }
      }  
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   Andy Turner    7 年前

    填充列表时只需插入空格:

    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]);
    }
    
        2
  •  1
  •   Community CDub    4 年前

    你可以用一个 word break 正则表达式:

    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+"'");
        }
    }
    

    这将为您保留所有空间。

    '你好'

    '有'

        3
  •  -2
  •   Crack Only    7 年前
    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(" "); 
              }
          }