For Programmers: Free Programming Magazines  


Home > Archive > C# > February 2005 > Extracting name/value pairs from a string









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

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.

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com