简体   繁体   中英

Detect last iteration in for-each loop in Java

There's a program I'm working on which deals with sentences, words and punctuations. It removes excess spaces from the sentences.

This is my code:

import java.util.*;
class Prog10
{
    static void main()
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a sentence:");
        String out="";        
        for(String i:sc.nextLine().split("[\\s]"))
            out+=i+(<last-iteration-condition>?"":" ");  //Using regex to clean excess spaces
        System.out.print(out);
    }
}

I'm wanting to detect the last iteration without any new additions to code except for the boolean condition. No as an answer would also suffice.

There is no way to determine if it is the last iteration of the loop, directly.

If you know the length of the array/Iterable that you are iterating, you can count the number of iterations, and do something when you know it is the last one, but this somewhat defeats the point of the enhanced for loop.

It is pretty easy to determine if it is the first iteration of the loop, however:

boolean isFirstIteration = true;
for (String i : someIterable) {
  // Do stuff.

  isFirstIteration = false;
}

You can use this in your case, by appending the space first :

String delim = "";
for(String i:sc.nextLine().split("[\\s]")) {
  out += delim + i;      
  delim = " ";
}

The delim variable is initially the empty string, so you don't insert anything on the first iteration. However, it is then set to a space, so a space is inserted on every subsequent iteration, then your i string.

Mind you, String.join(" ", sc.nextLine().split(...)) would be easier.

This is what I've come up with:

String out="";
for(String i:sc.nextLine().split("[\\s]"))        
    out+=(out.isEmpty()?"":" ")+i;  
System.out.print(out);           

Instead of re-inventing the wheel, you should use a StringJoiner to join the strings together.

StringJoiner out = new StringJoiner(" ");        
for(String i:sc.nextLine().split("[\\s]"))
    out.add(i);
System.out.print(out.toString());

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