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.

1 Answer 1

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.

1
  • My only issue was for whisper - I'd have to rejoin the message. I guess there's not really any other way Commented Aug 25, 2015 at 12:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.