java 消除最后一个逗号和空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35999914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:52:11  来源:igfitidea点击:

Eliminating Last Comma & Space

java

提问by Luke Harding

Here is original prompt:

这是原始提示:

"Write a for loop to print all NUM_VALS elements of array hourlyTemp. Separate elements with a comma and space. Ex: If hourlyTemp = {90, 92, 94, 95}, print: 90, 92, 94, 95

"编写一个 for 循环来打印数组 hourlyTemp 的所有 NUM_VALS 元素。用逗号和空格分隔元素。例如:如果 hourlyTemp = {90, 92, 94, 95},打印:90, 92, 94, 95

Note that the last element is not followed by a comma, space, or newline."

请注意,最后一个元素后面没有逗号、空格或换行符。”

Here is my code:

这是我的代码:

import java.util.Scanner;

public class PrintWithComma {
    public static void main (String [] args) {
        final int NUM_VALS = 4;
        int[] hourlyTemp = new int[NUM_VALS];
        int i = 0;

        hourlyTemp[0] = 90;
        hourlyTemp[1] = 92;
        hourlyTemp[2] = 94;
        hourlyTemp[3] = 95;

        for (i = 0; i < NUM_VALS; i++) {
            System.out.print(hourlyTemp[i] + ", ");
        }

        System.out.println("");

        return;
    }
}

My output is "90, 92, 94, 95, " when it should be "90, 92, 94, 95"

我的输出是 "90, 92, 94, 95, " 而它应该是 "90, 92, 94, 95"

How do i eliminate the last comma and space?

我如何消除最后一个逗号和空格?

采纳答案by Atri

Check if the last iteration is reached. If not print the comma, otherwise don't.

检查是否达到了最后一次迭代。如果不打印逗号,否则不要打印。

Replace :

代替 :

for (i = 0; i < NUM_VALS; i++) {
     System.out.print(hourlyTemp[i] + ", ");
}

With:

和:

for (i = 0; i < NUM_VALS; i++) {
     if (i == (NUM_VALS - 1)) System.out.print(hourlyTemp[i]);
     else System.out.print(hourlyTemp[i] + ", ");
}

回答by fukanchik

Generally you don't know number of values to print up-front (but in your case it's 4). So it is easier to print separator beforeinstead of after. No ifs:

通常,您不知道要预先打印的值的数量(但在您的情况下为 4)。所以更容易打印分隔符before而不是after. 没有if

String sep="";
for (i = 0; i < NUM_VALS; i++) {
     System.out.print(sep + hourlyTemp[i]);
     sep=", ";
  }

Trick is - first time there is nothing to separate hence separator is empty, later - ", ";

技巧是 - 第一次没有什么可以分开的,因此分隔符是空的,后来 - ", ";

Fits into register, saves branch predictor's work. Calculating if (i == last_value)is not 0 cost as well.

适合寄存器,保存分支预测器的工作。计算if (i == last_value)也不是0成本。

回答by Andrew Tobilko

String delimiter = ", ";

The first way is using java.util.StringJoiner. Additionally, you may specify a prefix and suffix of a result string (for example, (delimiter, "[", "]")).

第一种方法是使用java.util.StringJoiner. 此外,您可以指定结果字符串的前缀和后缀(例如,(delimiter, "[", "]"))。

StringJoiner joiner = new StringJoiner(delimiter);
for (int i : hourlyTemp) joiner.add(Integer.toString(i));
System.out.println(joiner.toString());

The second way is using Stream API.

第二种方式是使用 Stream API。

Arrays.stream(hourlyTemp)
            .map(i -> i.toString())
            .collect(Collectors.joining(delimiter));

Or the most boring way:

或者最无聊的方式:

for (i = 0; i < NUM_VALS;) 
    System.out.print(hourlyTemp[i] + (i++ != (NUM_VALS - 1) ? delimiter : ""));

回答by Matthew Wright

As an example, you can put a conditional and just print a blank space once you reach the end.

例如,您可以放置​​一个条件,并在到达末尾时只打印一个空格。

for(int i=0; i<10; i++) {
    System.out.print(i + (i < 10-1 ? ", " : ""));
}

回答by Andy Turner

Split up the value printing and the comma-space printing into two separate statements, and don't print the comma-space for the last value:

将值打印和逗号空间打印拆分为两个单独的语句,并且不要打印最后一个值的逗号空间:

System.out.print(hourlyTemp[i]);
if (i + 1 < NUM_VALS) {
  System.out.print(", ");
}

Alternatively, print the first value outside the loop, then print the comma-space first inside the loop:

或者,在循环外打印第一个值,然后在循环内首先打印逗号空间:

System.out.print(hourlyTemp[0]);
for (int i = 1; i < NUM_VALS; ++i) {
  System.out.print(", " + hourlyTemp[i]);
}

回答by Ramanlfc

check if ihas reached the last iteration.

检查是否i已到达最后一次迭代。

for (i = 0; i < NUM_VALS; i++) {
        if (i == (NUM_VALS - 1))
            System.out.print(hourlyTemp[i]);
        else
            System.out.print(hourlyTemp[i] + ", ");
    }