| Author |
Extracting name/value pairs from a string
|
|
| Joel Thornton 2005-02-11, 8:58 pm |
| We have String.Split() for turning strings into string-arrays. Is there
something analogous in the .Net libraries for turning strings into
NameValueCollections?
I wrote the below code to do it, but it sure seems like this kind of
thing would already be present in .Net and I've just missed it
entirely.
========================================
===================
NameValueCollection ExtractNameValueCollection(string source, char
outerDelimiter, char innerDelimiter)
{
NameValueCollection output = new NameValueCollection();
string[] pairs = source.Split(outerDelimiter);
// turn innerDelimiter into a char[] array because that's all
// String.Split() will take if you want to use the count arg
char[] innerSplitter = { innerDelimiter };
foreach (string pair in pairs)
{
string[] elements = pair.Split(innerSplitter, 2);
output.Add(
elements[0],
elements.Length == 2 ? elements[1] : null
);
}
return output;
}
========================================
===================
Comments on the above code are also very appreciated, even if it really
is redundant :D
Joel
| |
| geeksgk@yahoo.com 2005-02-16, 4:04 am |
| May be I got you wrong.
Else the following should work
NameValueCollection ExtractNameValueCollection(string strName, str
StrValue)
{
NameValueCollection output = new NameValueCollection();
output.Add(strName, strValue)
return output;
}
| |
| Joel Thornton 2005-02-16, 4:04 am |
| Actually what I want to do is turn a string such as this
"a=2&b=5&c=10"
into the name value pairs
a 2
b 5
c 10
Is there already a function to do this in .Net? No it isn't hard to
write but why reinvent any wheels :)
Joel
| |
| Keenan Newton 2005-02-16, 4:04 am |
| I don't think there is a function to do this.
| |
| csharp.general 2005-02-16, 4:01 pm |
| I think the better way to do this should be the regular expressions.
The method input should be the regular expression "&" or its ascii
value and should be able to create ENum from it and should be able to
return the Enum to be more genreic service.
| |
| csharp.general 2005-02-21, 3:58 am |
| I think the better way to do this should be the regular expressions.
The method input should be the regular expression "&" or its ascii
value and should be able to create ENum from it and should be able to
return the Enum to be more genreic service.
|
|
|
|