[SOLVED] Split string into first word and create a String[] of the rest

Discussion in 'Plugin Development' started by r3Fuze, Nov 7, 2011.

Thread Status:
Not open for further replies.
  1. What I'm trying to do is splitting a String into a String of the first word and a String[] of the rest.

    Example:

    And here is what I want to have in the end:


    It's kinda like in onCommand.
    Code:java
    1. public boolean onCommand(CommandSender sender, Command command, String label, String[] args);

    firstWord = label and otherWords = args.
     
  2. Offline

    Taco

    Using args as your original String, try something like this:

    String first = args.substring(0,args.indexOf(" "));
    String[] theRest = args.substring(args.indexOf(" "),args.length()).split(" ");

    It's a bit messy and completely off the top of my head, but it may work.
     
    r3Fuze likes this.
  3. I tried something like that, but now my problem is when the original String is just one word it gives me StringIndexOutOfBoundsExceptions. I tried checking for null and stuff but I can't figure it out (I'm still kinda new to Java)
     
  4. Offline

    Taco

    if(args.split(" ").length == 0)

    Maybe? I forget if a null array will return a length.
     
  5. Hmm, i tried this:
    Code:java
    1. System.out.println(args.split(" ").length > 0);

    It returns true when it's more than one word but comes with an exception when it's just one word.

    I tried looking at the Bukkit source to see where it does the stuff for onCommand so I can borrow that code, but I couldn't find it. If someone can link me to the correct class on github, I'd be happy.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 21, 2016
  6. Offline

    nisovin

    Something like this should work:
    Code:
    String myString = "This is my awesome string";
    String[] temp = myString.split(" ");
    String firstWord = temp[0];
     String[] otherWords = Arrays.copyOf(temp, 1, temp.length);
    
     
    r3Fuze likes this.
  7. That worked, thanks!
     
  8. Offline

    AoH_Ruthless

    Abigail111
    This is an extremely old thread you are reopening. For future reference, it may be better to create your own.

    But, can you post your whole code? We can't help you without it.
     
Thread Status:
Not open for further replies.

Share This Page