Getting anything after a certain argument, and making that a joint string

Discussion in 'Plugin Development' started by Drkmaster83, Nov 22, 2012.

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

    Drkmaster83

    So, say that I wanted anything after args[0] to be a string to be sent. Rather than checking for 40 different strings, do I use a for loop or...?

    I know that it probably sounds like I'm creating a message command, but it has something to do with setting the display tag for NBT stuff (Lore and Name), so... Please help! It would be much appreciated! :)
     
  2. Offline

    kiwhen

    You can use a stringBuilder-object for this sort of thing, or just add each string into another "complete" string. Either way requires some sort of looping, preferably a for-loop.

    Here's how to work the stringBuilder:
    Code:
    // Create object:
    StringBuilder sb = new StringBuilder();
     
    // You need some kind of string, usually just one word:
    String word = "textFragment";
     
    // ... and add it to the stringBuilder:
    sb.append(word);
     
    // Get the complete string:
    String someVariable = sb.toString();
    
    This is my own implementation of the latter option:
    Code:
    public static String composeMessage(String[] fragments, int startIndex, int trimRear) {
            String text = "";
         
            for(int i = startIndex; i < (fragments.length - trimRear); i++) {
                text += fragments[i] + " ";
            }
            // Strip trailing whitespace
            text = text.substring(0, text.length() - 1);
            return text;
        }
    
    Using this method, I can compose a message from a set of fragments (usually what you get in the args-array for commands like /msg <player> <message>), and specify what index I want to start from, and also if I want to cut off some words at the end. I use this for various purposes, for example if I know that a set of arguments contain something useful at the beginning and the end, and text in the middle.

    Edit: A quick note on why I use the substring-method over the usual trim-method; trim removes all whitespace surrounding the string in question. I'm not really interested in that, I just want to remove the one, single whitespace created by the composeMessage-method.

    Also, keep in mind that some situations may cause errors, like when the method is called with a fragment.length smaller than the startIndex. I perform these checks in other methods.
     
Thread Status:
Not open for further replies.

Share This Page