Rather than having two separate counters, I recommend starting by taking the length of the array and using a counter to print a comma while the counter is less than the number of total items in the array. That way, when you finish you’ll have one less comma than array item, and you won’t have a comma at the end of what you’ve printed.
This is kind of involved but, since you really don’t want to have the comma at the end of what you’ve printed, it may best fit your needs.
Here’s some pseudocode based on what you wrote above:
// the length of the array needs to be a constant because depending on
// what your code does it may change the array length as your loop runs
const arrayLength = the length of your array when you start
int commaCount = 0
foreach(string str in array1)
{
Schema Code
Schema Code
if (commaCount < (arrayLength -1))
// (< arrayLength -1) because then your last comma will reach
// (arrayLength -1) and then not increase any more the last time around
{
print a comma
}
}
Let me know if that helps.
(Please disregard my syntax. This is pseudocode, so definitely don’t copy and paste what I just wrote.)
2
solved ForEach loop counter [duplicate]