C# 在第一个空格处分割字符串
对于聊天机器人,如果有人说“!say”,它会在空格后背诵你说的话。简单 输入示例:C# 在第一个空格处分割字符串,c#,regex,string,split,C#,Regex,String,Split,对于聊天机器人,如果有人说“!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 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的重载,该重载有一个“最大”参数 就是这个: 看起来像:
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 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
(s,2)
中的s
不应该是字符吗?没有过多的分割获取(char,int)。你可能是指s.Split(new[]{''},2)
@StefanMonov它的工作!!你是对的,请通过添加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