Fabrizzio Reumann
Fabrizzio Reumann

Reputation: 43

Get the piece of text before a word on a string C#

I have done some research to make a kind of console for Unity and what i was been looking for is to try to get arguments from a command line, like:

givemoney -m 1000

And i found this code:

public string command = "givemoney -m 1000";
string arg = "-m ";
int ix = command.IndexOf(arg);
if (ix != -1)
{
    string moneyTG = command.Substring(ix + arg.Length);
    Debug.Log(moneyTG);
}

"moneyTG" returns 1000 It works great, but only if the command has just 1 argument. E.G.: If a put

givemoney -m 1000 -n 50

moneyTG will return 1000 -n 50

How do i remove the other part of the command?

Upvotes: 2

Views: 816

Answers (2)

Steven Palmer
Steven Palmer

Reputation: 300

Assuming you want the easiest solution and that all the elements of the command are separated by spaces, then consider using Split to separate out the elements into their own array (note - error checking omitted for brevity so don't use this without adding some!):

string command = "givemoney -m 1000";
string [] parts = command.Split(' ');
string arg = "-m";
int ix = Array.IndexOf(parts, arg);
if (ix != -1)
{
    string moneyTG = parts[ix + 1];
    Debug.Log(moneyTG);
}

The above example simply breaks up the command into three parts of which the second (parts[1]) will be -m, and thus you can grab the part after that to obtain the money value. Anything else will be ignored.

Upvotes: 0

Moo-Juice
Moo-Juice

Reputation: 38810

I think what you actually want is some sort of command map.

Dictionary<string, Action<string[]>> commands = new Dictionary<string, Action<string[]>>(StringComparison.OrdinalIgnoreCase);

commands["command1"] = (args) => { /* Do something with args here */ };
commands["givemoney"] = (args) => {
    if(args.Length == 2) {
        // args[1] = -m
        // args[2] = 1000
    }
};

// etc...

string example = "givemoney -m 1000";
string[] parts = example.Split(' ');
if(parts.Length > 0) {
    string cmd = parts[0];
    Action<string[]> command;
    if(commands.TryGetValue(cmd, out command))
         command(parts);
}

Upvotes: 1

Related Questions