【问题标题】:How to remove trailing whitespaces at the end of each line?如何删除每行末尾的尾随空格?
【发布时间】:2020-06-30 11:36:20
【问题描述】:

我正在 Dcoder 中尝试挑战,我的答案与预期的输出相同,但是我认为问题在于给定的情况,即删除每行末尾的尾随空格。

说清楚,这就是问题所在:

您需要将此模式打印到N,例如N = 3

预期输出:

1
1 2
1 2 3

不要在每行的末尾留下空格!

这是我的代码:

String sp = " ";
for (int rows = 1; rows <= range; rows++) { //rows
    for (int cols = 1; cols <= rows; cols++) {
        System.out.print(Integer.toString(cols) + sp);
    }
    System.out.println(sp.trim());
}

我尝试连接Integer.toString(cols)sp 然后另一个sp.trim() 输出也相同,但挑战并没有说它是正确的,为什么会这样?任何人都可以解释或我的代码有问题吗?

【问题讨论】:

    标签: java string whitespace


    【解决方案1】:

    你来了

    int range = 3;
    for(int rows = 1; rows <= range; rows++ ) {
        for(int cols = 1; cols <= rows; cols++ ) {
            if (cols == rows) {
                System.out.println(Integer.toString(cols));
            } else {
                System.out.print(Integer.toString(cols) + " ");
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您将在第二个 for 循环中的每个数字后附加空格 sp。这就是为什么打印出行时会有一个尾随空格。

      您有多种选择,例如使用 StringBuilder.append() 值,然后打印 toString().trim(),但这是您的代码的一个非常简单的扩展,我只是将 range 硬编码为 4

      public static void main(String[] args) {
          String sp = " ";
      
          for (int rows = 1; rows <= 4; rows++) {
              for (int cols = 1; cols <= rows; cols++) {
                  // here you need to find out if it is the last number to be printed
                  if (cols == rows) {
                      // if it is, just print that number
                      System.out.print(Integer.toString(cols));
                  } else {
                      // otherwise print the number and the whitespace
                      System.out.print(Integer.toString(cols) + sp);
                  }
              }
              // force a linebreak
              System.out.println();
          }
      }
      

      哪个输出

      1
      1 2
      1 2 3
      1 2 3 4
      

      替代解决方案:

      public static void main(String[] args) {
          for (int rows = 1; rows <= 4; rows++) {
              StringBuilder lineBuilder = new StringBuilder();
              for (int cols = 1; cols <= rows; cols++) {
                  if (cols == rows) {
                      lineBuilder.append(Integer.toString(cols));
                  } else {
                      lineBuilder.append(Integer.toString(cols)).append(" ");
                  }
              }
              System.out.println(lineBuilder.toString());
          }
      }
      

      【讨论】:

      • 该死。哈哈。我正在尝试使用 charAt 并将其转换。代码就这么简单?啊哈我明白了,自从我上次编程以来已经有很长时间了。非常感谢!我知道我的错误该死! ?谢谢谢谢。它奏效了。
      • 但我有点好奇使用 charAt 来实现它是否可能?但我想这要容易得多。
      • @user13216654 您的目标到底是什么?删除尾随空格? 我不认为 (1.)删除尾随空格比不添加它更好,(2.) 当有String.substring()StringBuilder.removeCharAt()(3.) 时,charAt() 将是删除字符的好选择,只要您只需要创建 String想打印简单的线条。
      【解决方案3】:
      String sp = " ";
      for (int rows = 1; rows <= 3; rows++){ //rows
       
          String pattern ="";
          for (int cols = 1; cols <= rows; cols++)
              pattern += Integer.toString(cols) + sp;
      
          System.out.println(pattern.trim());
      }
      

      【讨论】:

      【解决方案4】:

      Java 8 开始,您可以使用Collectors.joining 方法将字符串与中间的空格连接起来:

      int n = 5;
      IntStream.rangeClosed(1, n)
              // row of numbers
              .mapToObj(i -> IntStream.rangeClosed(1, i)
                      // number as string
                      .mapToObj(String::valueOf)
                      // join strings into one line
                      // with spaces in between
                      .collect(Collectors.joining(" ")))
              // output line by line
              .forEach(System.out::println);
      

      或者你也可以使用String.join方法,效果一样:

      int n = 5;
      for (int i = 1; i <= n; i++) {
          // row of numbers
          String[] row = new String[i];
          for (int j = 0; j < i; j++) {
              // number as string
              row[j] = String.valueOf(j + 1);
          }
          // join an array of strings into
          // one line with spaces in between
          System.out.println(String.join(" ", row));
      }
      

      输出:

      1
      1 2
      1 2 3
      1 2 3 4
      1 2 3 4 5
      

      另见:Adding a whitespace inside a List of strings?

      【讨论】: