【问题标题】:Divide a string at first space在第一个空格处分割一个字符串
【发布时间】:2012-02-20 18:48:43
【问题描述】:

对于聊天机器人,如果有人说“!say”,它会在空格后背诵你说的话。很简单。

示例输入:

!say this is a test

期望的输出:

this is a test

为了参数,字符串可以表示为ss.Split(' ') 产生一个数组。

s.Split(' ')[1] 只是空格后的第一个单词,有什么想法可以完全划分和获取第一个空格后的所有个单词吗?

我已经尝试过类似的方法:

s.Split(' ');
for (int i = 0; i > s.Length; i++)
{
    if (s[i] == "!say")
    {
        s[i] = "";
    }
}

输入是:

!say this is a test

输出:

!say

这显然不是我想要的:p

(我知道这个问题有几个答案,但没有一个是用 C# 编写的。)

【问题讨论】:

    标签: c# regex string split


    【解决方案1】:

    使用具有“最大”参数的 s.Split 的重载。

    就是这个: http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

    看起来像:

    var s = "!say this is a test";
    var commands = s.Split (' ', 2);
    
    var command = commands[0];  // !say
    var text = commands[1];     // this is a test
    

    【讨论】:

    • (s, 2) 中的s 不应该是字符吗?
    • Split take (char, int) 没有过载。你的意思可能是s.Split(new[] { ' ' }, 2)
    • @StefanMonov 它的工作!你是对的,请通过添加 new[] { ' ' } 来解释它为什么起作用
    【解决方案2】:

    您可以使用 string.Substring 方法:

    s.Substring(s.IndexOf(' '))
    

    【讨论】:

      【解决方案3】:
      var value = "say this is a test";
      return value.Substring(value.IndexOf(' ') + 1);
      

      【讨论】:

        【解决方案4】:

        此代码对我有用。我添加了 new [] 并且它可以工作

        var s = "!say this is a test";
        var commands = s.Split (new [] {' '}, 2);
        
        var command = commands[0];  // !say
        var text = commands[1];     // this is a test
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-10
          • 2012-01-08
          • 2013-04-19
          • 1970-01-01
          • 2012-05-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多