类似aaa?a=1&b=2&c=3&d=4,如何将问号以后的数据变为键值对

时间:2023-03-08 18:14:21
string result = "aaa?a=1&b=2&c=3&d=4";
string[] array = result.Split('?');
//string a = System.Web.HttpUtility.ParseQueryString(array[1]).Get("a");
System.Collections.Specialized.NameValueCollection abcd = System.Web.HttpUtility.ParseQueryString(array[1]);
string a = abcd.Get("a");
string b = abcd.Get("b");
string c = abcd.Get("c");
string d = abcd.Get("d");

ParseQueryString的内部实现(字符串截取):

 int num = (s != null) ? s.Length : 0;
System.Collections.Specialized.NameValueCollection a = new System.Collections.Specialized.NameValueCollection();
for (int i = 0; i < num; i++)
{
int startIndex = i;
int num4 = -1;
while (i < num)
{
char ch = s[i];
if (ch == '=')
{
if (num4 < 0)
{
num4 = i;
}
}
else if (ch == '&')
{
break;
}
i++;
}
string str = null;
string str2 = null;
if (num4 >= 0)
{
str = s.Substring(startIndex, num4 - startIndex);
str2 = s.Substring(num4 + 1, (i - num4) - 1);
}
else
{
str2 = s.Substring(startIndex, i - startIndex);
} a.Add(str, str2); if ((i == (num - 1)) && (s[i] == '&'))
{
a.Add(null, string.Empty);
}
}

点击链接学习:膜拜高手