字符串解析C#创建段?

时间:2012-08-14 18:03:02

标签: c#

我有一个字符串形式:

"company=ABCorp, location=New York, revenue=10million, type=informationTechnology"

我希望能够解析这个字符串并以

的形式获得“name”,“value”对

公司= ABCCorp

location =纽约等。

这可以是任何适合存储的数据结构。我想的可能是Dictionary<string, string>(),但我愿意接受建议。

在C#中有没有合适的方法?

编辑:我的最终目标是拥有这样的东西:

Array [company] = ABCCorp。 数组[位置] =纽约。

我们可以使用哪种数据结构来实现上述目标?我的第一个想法是字典,但我不确定我是否遗漏了什么。

感谢

4 个答案:

答案 0 :(得分:4)

使用String.SplitToDictionary,您可以:

var original = "company=ABCorp, location=New York, revenue=10million, type=informationTechnology";

var split = original.Split(',').Select(s => s.Trim().Split('='));

Dictionary<string,string> results = split.ToDictionary(s => s[0], s => s[1]);

答案 1 :(得分:3)

string s = "company=ABCorp, location=New York, revenue=10million, type=informationTechnology";
var pairs = s.Split(',')
        .Select(x => x.Split('='))
        .ToDictionary(x => x[0], x => x[1]);

对是具有键值对的Dictionary。唯一需要注意的是,您可能希望处理逗号和字符串之间的任何空格。

答案 2 :(得分:2)

这很大程度上取决于预期的语法。一种方法是使用String.Split: http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx

首先在逗号上拆分,然后迭代返回的字符串列表中的所有项目并将它们拆分为相等。

但是,这要求值中不存在逗号和相等?

答案 3 :(得分:1)

我假设一个弱的RegEx / LINQ背景,所以这是一种没有任何“特殊”的方法。

string text = "company=ABCorp, location=New York, revenue=10million, type=informationTechnology";

string[] pairs = text.Split(',');
Dictionary<string, string> dictData = new Dictionary<string, string>();

foreach (string currPair in pairs)
{
    string[] data = currPair.Trim().Split('=');

    dictData.Add(data[0], data[1]);
}

这要求除了作为分隔符之外,数据中不存在逗号(,)和等号(=)。

这很大程度上依赖于String.Split