[英]Delete whitespaces in the beginning of each line and end the end of the each line
[英]How to remove trailing whitespaces at the end of each line?
我正在 Dcoder 中尝试挑战,我的答案与预期的 output 相同,但是我认为问题出在给定情况下,即删除每行末尾的尾随空格。
说清楚,这就是问题所在:
您需要将此模式打印到
N
,例如N = 3
预期 Output:
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()
output 也是相同的,但挑战并没有说它是正确的,为什么会这样? 任何人都可以解释或我的代码有问题吗?
你有 go
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) + " ");
}
}
}
您在第二个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());
}
}
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());
}
自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));
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
另请参阅:在字符串列表中添加空格?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.