0

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.

4
  • 1
    It wouldn't: it must be at least 30 character long. But No is the correct answer. Commented Feb 20, 2018 at 7:18
  • 1
    docs.oracle.com/javase/8/docs/api/java/lang/… Commented Feb 20, 2018 at 7:21
  • Thanks, that was quick. By 30 characters long, are you referring to the additional code required? Commented Feb 20, 2018 at 7:21
  • @UtkarshVerma it's the minimal length of an answer Commented Feb 20, 2018 at 7:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That does add a bit of code, for example, the extra braces and a new String variable which I wanted to avoid but I think I'll have to use this method.
@Utkarsh if you're worried about adding one variable, you should really adopt a more efficient method of concatenating strings.
Thanks, I will look into it :smile:.
+1 getting used to checking for the first instead of the last iteration is very helpful when you start to code declaratively, for example concatenate strings in SQL.
0

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

Comments

0

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

1 Comment

Nice suggestion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.