Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
My only issue was for whisper - I'd have to rejoin the message. I guess there's not really any other way –  user2410532 Aug 25 at 12:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.