2

I am having trouble writing a simple command based system for a chatroom. I want users to be able to do chat actions such as

/j myChatRoom or /join myChatRoom

/w user12 Hello or /whisper user12 Hello

etc

I've spent a while and all I can come up with are crazy substring and indexof searches, trying to chop off pieces of the entire string and find a command and arguments. I feel like there could be a regex that could tell me if this string has one argument, for joining and leaving rooms, or two arguments, for private messages. I just can't think of a logical way.

tones31
  • 787
  • 1
  • 5
  • 13

1 Answers1

2

If it was me, I'd do something similar to the following, utilising split() and switch:

public void ProcessInput(string lineOfInput)
{
    string[] parts = lineOfInput.Split(' ');

    switch (parts[0])
    {
        case "/j":
        case "/join":
            JoinChannel(parts[1]);
            break;

        case "/w":
        case "/whisper":
            SendPM(parts);
            break;

        default:
            SendMessage(parts);
            break;
    }
}

There's no reason to go overly complex here.

Jack Scott
  • 1,374
  • 9
  • 9
  • My only issue was for whisper - I'd have to rejoin the message. I guess there's not really any other way – tones31 Aug 25 '15 at 12:32