1

I'm trying to separate each element in the vector with a comma bar the last. I've looked into using the String.Join method but I don't think that applicable in my situation.

string Room::displayWeapon() {
    string tempString = "Weapon in room = ";
    int sizeItems = (weaponsInRoom.size());
    if (weaponsInRoom.size() < 1) {
        tempString = "no items in room";
        }
    else if (weaponsInRoom.size() > 0) {
       int x = (0);
        for (int n = sizeItems; n > 0; n--) {
            tempString = tempString + weaponsInRoom[x].getShortDescription() ;
            x++;
            }
        }
    return tempString;
    }
  • 1
    `for(i = 0; i < w.size() - 1 ; ++i) res += w[i] + ","; res += w.back();` isn't suitable? – Zeta Mar 28 '14 at 16:42

2 Answers2

0

You can try something like this:

bool first = true;
for (int n = sizeItems; n > 0; n--) {
    if(!first) {
        tempString = tempString + ",";
    }
    tempString = tempString + weaponsInRoom[x].getShortDescription() ;
    x++;
    first = false;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Why would you use a condition inside of the for loop, where you could simply take the first item _before_ the loop and then use the same logic throughout the whole loop? (aka `tempString = w.back(); for(n = sizeItems - 1; n > 0; n--) tempString += "," + w[n];`) – Zeta Mar 28 '14 at 16:45
  • @Zeta 1. To make the principle clearer for the OP. Condition also could be `n == sizeItems`. 2. I wouldn't want to have to maintain the code to build part of the string doubled. – πάντα ῥεῖ Mar 28 '14 at 16:48
  • @Zeta Why not putting this as an additional answer? – πάντα ῥεῖ Mar 28 '14 at 16:49
0

If you want to keep it simple, there are two ways to think about it. You either take the first element and then place a comma before every following, or you take all the others and place a comma behind every single one.

Take first, place comma before

// ...
else if (weaponsInRoom.size() > 0) {
    tempString += weaponsInRoom.front().getShortDescription();
    for (std::size_t n = 1; n < weaponsInRoom.size(); ++n) {
        tempString += ", " + weaponsInRoom[n].getShortDescription();
    }
}
// ...

Place comma after every single one except the last

// ...
else if (weaponsInRoom.size() > 0) {
    for (std::size_t n = 0; n < weaponsInRoom.size() - 1; ++n) {
        tempString += weaponsInRoom[n].getShortDescription() + ", ";
    }
    tempString += weaponsInRoom.back().getShortDescription();
}
// ...
Zeta
  • 103,620
  • 13
  • 194
  • 236