我的问题包括如何拆分这样的字符串:
sudo service httpd restart
分为:
""List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2
\tdevice\r\n\r\n"
我已经尝试了这个但它会抛出错误"参数1:无法转换为' string'到''"
[n9887bc314,n12n1n2nj1jn2]
我想知道我做错了什么,因为我对c#很陌生。 非常感谢
答案 0 :(得分:1)
用 device 这个词拆分整个字符串,然后从中删除标签和新行。方法如下:
var wholeString = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
var splits = wholeString.Split(new[] { "device" }, StringSplitOptions.RemoveEmptyEntries);
var device1 = splits[1].Substring(splits[1].IndexOf("\n") + 1).Replace("\t", "");
var device2 = splits[2].Substring(splits[2].IndexOf("\n") + 1).Replace("\t", "");
答案 1 :(得分:1)
首先String.Split accept strings[] as delimiters
这是我的代码,希望它会有所帮助:
string input = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiterChars = {
"\r\n",
"\tdevice",
"List of devices attached"
};
var words = input.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
Console.WriteLine(word);
}
答案 2 :(得分:0)
你可以这样做:
string str = @"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] lines = str.Split(new[] { @"\r\n" }, StringSplitOptions.None);
string firstDevice = lines[1].Replace(@"\tdevice", "");
string secondDevice = lines[2].Replace(@"\tdevice", "");
答案 3 :(得分:0)
我已经做了第一次接种并且它有效,它可能有所帮助: 我把输入分开来寻找" / tdevice"然后在/ r / n之前清理每一个,包括/ r / n本身。它完成了这项工作,应该与您的adb输出一起使用。
修改强> 我重构了我的答案,考虑@LANimal答案(使用所有分隔符拆分),我尝试了这段代码并且有效。 (注意@用法)
static void Main(string[] args)
{
var inputString = @"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiters = {
@"\r\n",
@"\tdevice",
@"List of devices attached"
};
var chunks = inputString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = "[";
for (int i = 0; i < chunks.Length; i++)
{
result += chunks[i] + ",";
}
result = result.Remove(result.Length - 1);
result += "]";
Console.WriteLine(result);
Console.ReadLine();
}
我希望它有所帮助,
涓