Search code examples
javastringbotsirc

Java - How can I check for the next upcoming space in a string? (For IRC Bot)


Obviously, for an IRC bot, input is generated by a user typing a single string, usually with a command and a few arguments, each separated by a space. I am coding an IRC bot using Java and would like to parse arguments that might vary in character length and save them into multiple strings for use later. I would like to make a command that looks something like this:

bot.command argument1 argument2 argument3

and I want it to be so that if the message starts with bot.command, then user will store argument1, time will store argument2, and date will store argument3. The thing is, though, that argument1, argument2, and argument3 could vary in character length, so doing something like time = message.substring(33, message.length()) will stop reading at the end of the argument, but it won't always read the string where the argument3's text begins. I need to detect where the separator space is and start reading argument3 from one character after that. And I can't use If statements to determine what the arguments might be, because they could be anything. Here's a template, if the above paragraph isn't clear:

String message //= the IRC message and bot input
String user;
String time;
String date;
if (message.startsWith("bot.command")) {
    user = message.substring(13, detect next space here and stop reading one character before);
    time = message.substring(detect where previous space was and start one character after that, end before next space);
    date = message.substring(detect where previous space was and start one character after that, message.length());
}

I hope that kind of illustrates what I'm trying to do. Thank you for your help!


Solution

  • Edit (Removed StringTokenizer example) -

    Since StringTokenizer is apparently "legacy", I would use a Scanner like this -

    String message = "BOT.command USER_X    THIS_IS_A_TIME THIS_IS_A_DATE";
    String user = null;
    String time = null;
    String date = null;
    // Use toLowerCase - assuming it's case insensitive.
    if (message.toLowerCase()
        .startsWith("bot.command")) {
      Scanner st = new Scanner(message);
      if (st.hasNext()) {
        st.next();
      }
      if (st.hasNext()) {
        user = st.next();
      }
      if (st.hasNext()) {
        time = st.next();
      }
      if (st.hasNext()) {
        date = st.next();
      }
    }
    System.out.printf(
        "User = %s,  Time = %s, Date = %s\n", user,
        time, date);
    

    Output is

    User = USER_X,  Time = THIS_IS_A_TIME, Date = THIS_IS_A_DATE