简体   繁体   中英

How to remove trailing whitespaces at the end of each line?

I am trying a Challenge in Dcoder and my answer is same to the expected output however I am thinking that the problem is about the given situation to remove the trailing whitespaces at the end of each line.

To make it clear, this is the problem:

You need to print this pattern up to N , eg N = 3

Expected Output:

 1 1 2 1 2 3

Do not leave trailing spaces at the end of each line!

This is my Code:

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());
}

I tried concatenating Integer.toString(cols) and sp then another sp.trim() output is also the same but challenge doesn't say that its correct, why is this happening? Can anybody explain or is there something wrong with my code?

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

You are appending the whitespace sp after every number in your second for loop. That's why there is a trailing whitespace when you print out the lines.

You have several options, like using a StringBuilder and .append() the values and then print toString().trim() , but here's a very simple extension of your code where I just hard-coded the range by 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();
    }
}

which outputs

1
1 2
1 2 3
1 2 3 4

Alternative solution:

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());
}

Since Java 8 you can use Collectors.joining method to concatenate strings with whitespaces in between :

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);

Or you can use String.join method with the same effect:

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

See also: Adding a whitespace inside a List of strings?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM