[TUT] How to get all args into a single string

Discussion in 'Resources' started by iKeirNez, Sep 29, 2012.

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

    iKeirNez

    I have seen way to many plugins that do this kinda thing:

    Code:
    String allArgs;
    if (args.lengh > 0){
    allArgs = args[0];
    }
     
    if (args.lengh > 1){
    allArgs = allArgs + args[1];
    }
     
    if (args.length > 2){
    allArgs = allArgs + args[2]
    }
     
    ...etc
    
    There is a much easier, faster and more efficient way of doing this. There are many variations but this is what I personally use

    Code:
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < args.length; i++){
    sb.append(args[i]).append(" ");
    }
     
    String allArgs = sb.toString().trim();
    This code could be useful if you are programming a command to send a private message. If you wanted to start at the second argument incase you have a parameter for the target then you can do this.

    Code:
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < args.length; i++){
    sb.append(args[i]).append(" ");
    }
     
    String allArgs = sb.toString().trim();
    Hope this helps!

    Thanks stelar7 for the trim tip
     
    Markcrafter1 likes this.
  2. Offline

    stelar7

    Code:
    sb.append(args[i]).append(" ");
    and
    Code:
    sb.toString().trim();
    is even better
     
  3. Offline

    iKeirNez

    Ok thanks, I'll edit my post!
     
  4. Offline

    hawkfalcon

    I feel like this post is directed at me :3
     
    JOPHESTUS likes this.
  5. Offline

    iKeirNez

    Nope, it isn't. I haven't really looked at your code yet.
     
  6. Offline

    hawkfalcon

    :3 Let Icyene clean it up first :p
    Then if wont be so bad.
     
  7. Offline

    iKeirNez

    Haha ok
     
    hawkfalcon likes this.
  8. Offline

    Chlorek

    I used your method (my method, because I wrote exactly the same code) in my current project :D However - simple, usable and works ;]
     
  9. Offline

    iKeirNez

    Thanks, I am pretty sure any Intermediate+ Java programming will have thought of this!
     
  10. Offline

    Ixbitz

    Thx for explaining! Exactly what i needed:)
     
  11. Offline

    iKeirNez

    No problem, glad I could help!
     
  12. Offline

    libraryaddict

    I use

    Code:
    StringUtils.join(args, " ")
     
  13. Offline

    iKeirNez

    Yeah I used to use that and then someone told me that Apache Commons isn't included in Bukkit. But they are wrong!
     
  14. Offline

    jacklin213

    wat does trim do XD
     
  15. Offline

    iKeirNez

  16. Offline

    jacklin213

    Ahhhh ty
     
Thread Status:
Not open for further replies.

Share This Page