mt2
mt2

Reputation: 9

How to change the last iteration in an array?

I have an array that prints out the number with a comma attached but for the last iteration, I don't want there to be a comma attached to the last number. Is there a way that I can create an if statement that only applies to the last iteration? Its java.

Upvotes: 0

Views: 67

Answers (4)

Pranalee
Pranalee

Reputation: 3409

create a string by iterating and appending comma, and then do substring. "1,2,3,".substring(0,L-1) where L is length.

Upvotes: 0

Bill K
Bill K

Reputation: 62769

There are often much better ways depending on your language.

In Java 8 you should be able to use String.join(", ", listOfItems)

There are a few other Join methods that work the same way in older versions of Java but I always have trouble finding them.

In Groovy and Ruby I believe all the collections have join methods that work like this:

assert "this is a test".split(" ").join(", ") == "this, is, a, test"

Upvotes: 2

Scott Semyan
Scott Semyan

Reputation: 225

Just print the , before the item and don't do it for the first one. You didn't mention the language but Java/C/C#/Javascript solution would be something like:

for (int x = 0; x < ListSize; x++)
{
   if (i > 0)
   {
       print ",";
   }
   print list[i];
}

Upvotes: 1

Born2Code
Born2Code

Reputation: 1075

you can check on the last item of the array in most languages. Though, it seems your issue is probably a design and not syntax issue. Any how, here is an example in javascript

var ar = ['1', '2', '3', '4', '5'];
for (var i = 0; i < ar.length; i++) {

  if (i == ar.length - 1) {
    console.log(ar[i]);
  } else {
    console.log(ar[i] + ',');
  }
}

Upvotes: 0

Related Questions