簡體   English   中英

在第一個空格處划分一個字符串

[英]Divide a string at first space

對於聊天機器人,如果有人說“!說”它會在空間后背誦你所說的內容。 簡單。

輸入示例:

!say this is a test

期望的輸出:

this is a test

為了論證,字符串可以表示為s s.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#從我搜索的地方寫的。)

使用具有“最大”參數的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

您可以使用string.Substring方法:

s.Substring(s.IndexOf(' '))
var value = "say this is a test";
return value.Substring(value.IndexOf(' ') + 1);

這段代碼對我有用。 我添加了新的[]並且它有效

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM