首页 > 解决方案 > 如何删除每行末尾的尾随空格?

问题描述

我正在 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()输出也相同,但挑战并没有说它是正确的,为什么会这样?任何人都可以解释或我的代码有问题吗?

标签: javastringwhitespace

解决方案


给你

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

推荐阅读