2

如何拆分以下字符串

string s = "username=bill&password=mypassword";

Dictionary<string,string> stringd = SplitTheString(s);

这样我就可以按如下方式捕获它:

string username = stringd.First().Key;
string password = stringd.First().Values;

请告诉我。谢谢

4

6 回答 6

6

您可以像这样填充字典列表:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
string s = "username=bill&password=mypassword";

foreach (string x in s.Split('&'))
{
    string[] values = x.Split('=');
    dictionary.Add(values[0], values[1]);
}

这将允许您像这样访问它们:

string username = dictionary["username"];
string password = dictionary["password"];

注意:请记住,此函数中没有验证,它假定您的输入字符串格式正确

于 2012-05-10T15:59:46.150 回答
5

看起来您正在尝试解析查询字符串 - 这已经内置,您可以使用HttpUtility.ParseQueryString()它:

string input = "username=bill&password=mypassword";
var col = HttpUtility.ParseQueryString(input);
string username = col["username"];
string password = col["password"];
于 2012-05-10T16:01:25.320 回答
2

我认为类似的东西应该可以

public Dictionary<string, string> SplitTheStrings(s) {
    var d = new Dictionary<string, string>();  
    var a = s.Split('&');
    foreach(string x in a) {
        var b = x.Split('=');
        d.Add(b[0], b[1]);
    }
    return d;
}
于 2012-05-10T16:00:28.910 回答
1
        var splitString = "username=bill&password=pass";
        var splits = new char[2];
        splits[0] = '=';
        splits[1] = '&';
        var items = splitString.Split(splits);
        var list = new Dictionary<string, string> {{items[1], items[3]}};

        var username = list.First().Key;
        var password = list.First().Value;

这也是我的工作

于 2012-05-10T16:08:12.620 回答
1

如果键不会重复

var dict = s.Split('&').Select( i=>
{
    var t = i.Split('=');
    return  new {Key=t[0], Value=t[1]};}
).ToDictionary(i=>i.Key, i=>i.Value);

如果键可以重复

    string s = "username=bill&password=mypassword";
    var dict = s.Split('&').Select( i=>
    {
        var t = i.Split('=');
        return  new {Key=t[0], Value=t[1]};}
    ).ToLookup(i=>i.Key, i=>i.Value);
于 2012-05-10T16:18:40.713 回答
0

其他答案更好,更容易阅读,更简单,更不容易出现错误等,但另一种解决方案是使用这样的正则表达式来提取所有键和值:

MatchCollection mc = Regex.Matches("username=bill&password=mypassword&","(.*?)=(.*?)&");

匹配集合中的每个匹配项都有两个组,一组用于键文本,一组用于值文本。

我不太擅长正则表达式,所以我不知道如何在不将尾随'&'添加到输入字符串的情况下使其匹配......

于 2012-05-10T16:12:28.233 回答