views:

43

answers:

4

How to Split and strip X string values into separate variables?

X has string value of

itemA=myvalue&itemB=anothervalue&itemC=andanother

I have 3 strings (var1,var2,var3) to hold the values of the stripped values.

Find in string X "itemA=" copy everything after "=" character until "&" character OR if no "&" character is found copy until end of string (store this value into var1)

Find in string X "itemB=" copy everything after "=" character until "&" character OR if no "&" character is found copy until end of string (store this value into var2)

Find in string X "itemB=" copy everything after "=" character until "&" character OR if no "&" character is found copy until end of string (store this value into var3)

+2  A: 
string X =  "itemA=myvalue&itemB=anothervalue&itemC=andanother";
string[] variables = X.Split('&');
 foreach (var variable in variables)
 {
    string key = variable.Split('=')[0]; //Ex. itemA
    string value = variable.Split('=')[1]; //Ex.myvalue
    //do whatever you want with the value 
}
Amgad Fahmi
+1 beat me. I'd replace "" with X to match the question, and var could easily be string to avoid a lack of c# 3 ;)
Zhaph - Ben Duguid
This solution does not allow for specifying the keys.the key might be arranged in different order and you wouldn't be able to determine the difference between the keys.
K001
that's right, i agree :)
Amgad Fahmi
+5  A: 

Using System.Web.HttpUtility. You can use this even in a non Web application, if a reference to System.Web is not a problem.

var values = HttpUtility.ParseQueryString(
    "itemA=myvalue&itemB=anothervalue&itemC=andanother");

Console.WriteLine(values["itemA"]);
Console.WriteLine(values["itemB"]);

You can list all the keys:

foreach (var key in values.AllKeys)
{
    Console.WriteLine(key);
}
João Angelo
but here you have to know the key to retrieve the value,what if i want to get list of keys ?
Amgad Fahmi
the solution didn't work,
K001
@Khou, why it didn't work?
João Angelo
+1  A: 

If its asp.net application, you can use QueryString.

string value1 = Request.QueryString["itemA"];
string value2 = Request.QueryString["itemB"];
string value3 = Request.QueryString["itemC"];
šljaker
A: 
string[] pairs = mystring.Split( '&' );
var1 = pairs[0].Split( '=' )[1];
var2 = pairs[1].Split( '=' )[1];
var3 = pairs[1].Split( '=' )[1];
Mikael Svenson