Separating Array indexes with a comma

Discussion in 'Plugin Development' started by Razorcane, Nov 25, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    Razorcane

    I have getOnlinePlayers(); stored in a String[], and I want to output them on the screen like so:

    player1, player2, player3

    Notice how each player is separated with a comma, but the last one is not. I know it can be done, but I haven't run across any functions that would allow me to do so. Any help would be appreciated.

    EDIT: I already know I need a for loop to output it as a string, there's no need to include that.
     
  2. Out of my head
    Code:
    String newString = "";
    for (String s : stringArray) {
        newString += s + ", ";
    }
    if (newString.length() > 0) {
        newString = newString.substring(0, newString.length() - 2);
    }
    
    The part you want is the substring part.
     
    r3Fuze likes this.
  3. Offline

    Razorcane

    Why does it need to be -2? The extra space at the end?
     
  4. -2 because of the text ", " that is being added at the end. Maybe it's -1 (because of how indexes work,) but just test it out :)

    Array = "Player1", "Player2"
    newString before the substring will be "Player1, Player2, "
    The substring removes the last two characters so it will be "Player1, Player2"
     
  5. Offline

    Razorcane

    -2 seems to work just fine, it removes the comma and the space at the end. Thanks for the help. :)
     
  6. Just give me a like or something. I'm happy I could help! :D
     
    Razorcane and r3Fuze like this.
  7. Offline

    desht

    Don't use string concactenation inside for loops. It's very inefficient.

    Use StringBuilder, or perhaps even easier, Joiner:
    Code:
    String newString = Joiner.on(", ").join(Bukkit.getServer().getOnlinePlayers());
    
    Joiner comes from the Guava library, which is included in Bukkit.
     
    dadaemon likes this.
  8. There... Learned something new! Thanks @desht !
     
  9. Offline

    digga

    Code:
    String str="";
    for(Player player : getOnlinePlayers()) {
    str += player.getName()+",";
    }
    
    log.info(str);
    Think this should work
     
  10. Offline

    iffa

    Not really. You would have an unneeded , after the last player.
     
  11. Offline

    desht

    Not to mention that it's four lines of code where one would do, and it's efficiency is O(n^2) instead of O(n). See my previous post.
     
Thread Status:
Not open for further replies.

Share This Page