C# 如何将字符串与空格一起拆分?
如何拆分上述字符串,以便获得包含6个元素的字符串数组,从而C# 如何将字符串与空格一起拆分?,c#,string,split,C#,String,Split,如何拆分上述字符串,以便获得包含6个元素的字符串数组,从而 string arg = "-h 127.0.0.1 -p 50 cssbct \"hey man!\"\r\n"; ? 我尝试了以下方法: splittedArgs[0] == "-h" splittedArgs[0] == "127.0.0.1" splittedArgs[0] == "-p" splittedArgs[0] == "50" splittedArgs[0] == "cssbct" splittedArgs[0]
string arg = "-h 127.0.0.1 -p 50 cssbct \"hey man!\"\r\n";
?
我尝试了以下方法:
splittedArgs[0] == "-h"
splittedArgs[0] == "127.0.0.1"
splittedArgs[0] == "-p"
splittedArgs[0] == "50"
splittedArgs[0] == "cssbct"
splittedArgs[0] == "\"hey man!\""
它不起作用
有什么想法吗
注意:字符串也可以采用以下形式:
args = args.Replace('\r', ' ');
args = args.Replace('\n', ' ');
string[] splittedArgs = args.Split(new string[] { " " },
StringSplitOptions.RemoveEmptyEntries);
元素必须相应地保持序列。您可以使用正则表达式在空白处拆分 使用
“
对字符串进行拆分时,您的行是正确的,但给出了以下字符串示例:
string arg=“-h127.0.0.1-p50 cssbct\”嘿,伙计\“\r\n”代码>,存在可变数量的空白
A可用于根据不同的空白分隔字符串。下面我们使用\\s+
来实现这一点
您已经看了无数的问题了吗?此机制无法拆分以下内容:“POST/cssbct HTTP/1.0\r\nHost:locationserver\r\n内容长度:72\r\n\r\nname=cssbct&location=RB-999”
string arg = "-h 127.0.0.1 cssbct \"hey man!\" -p 50\r\n";
string arg = "cssbct \"hey man!\" -p 50 -h 127.0.0.1 \r\n";
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string arg = "-h 127.0.0.1 -p 50 cssbct \"hey man!\"\r\n";
string[] arrArgs = Regex.Split(arg, "\\s+");
foreach(string s in arrArgs){
Console.WriteLine(s);
}
}
}