在字符串C#上的单词之前获取一段文本

时间:2017-02-08 11:36:49

标签: c# string unity3d

我做了一些研究,为Unity制作一种控制台,我一直在寻找的是尝试从命令行获取参数,例如:

givemoney -m 1000

我找到了这段代码:

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"返回1000 它工作得很好,但只有命令只有一个参数。 E.G。:如果放了

givemoney -m 1000 -n 50
moneyTG将返回1000 -n 50

如何删除命令的其他部分?

2 个答案:

答案 0 :(得分:1)

我认为你真正想要的是某种命令图。

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);
}

答案 1 :(得分:0)

假设您想要最简单的解决方案并且命令的所有元素都用空格分隔,那么考虑使用Split将元素分离到它们自己的数组中(注意 - 为简洁起见省略了错误检查,所以不要使用添加一些!):

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);
}

上面的例子简单地将命令分成三部分,其中第二部分(部分[1])将是-m,因此你可以在之后获取部分以获得金钱价值。其他任何东西都会被忽略。

相关问题