Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing text ?

Status
Not open for further replies.

elhaix

Programmer
Jul 31, 2006
115
CA
I've got the following possibilities being returned by Request.UrlReferrer.ToString();

Code:
[URL unfurl="true"]http://test.myserver.com/searchresult1.asp?hl=en&lr=&rls=ADBS,ADBS:2006-36,ADBS:en&q=create+a+website&btnG=Search[/URL] - q is @ end

[URL unfurl="true"]http://test.myserver.com/searchresult2.asp?p=create+a+webpage&fr=FP-tab-web-t400&toggle=1&cop=&ei=UTF-8[/URL] - p is @ beginning

The problem is that it's in the string format. I want to be able to grab parameters like how we do Request.QueryString["param"].

Can someone throw some quick code up here for that please?



Thanks.
 
Simple. You need to break your string up into a hashtable.

string url =
start by getting rid of the part of the string that you don't care about (up to the ?)

so

int index = url.IndexOf("?");
string vars = url.SubString(index, url.Length - index);

so now your vars string should look like:

hl=en&lr=&rls=ADBS,ADBS:2006-36,ADBS:en&q=create+a+website&btnG=Search

Now you need to split by &

string[] pairs = vars.Split("&");

which should give you an array of strings like so:

hl=en
lr=
rls=ADBS,ADBS:2006-36,ADBS:en
q=create+a+website
btnG=Search

and finally, split each of those by "=" and slap it into a hashtable.

Hashtable variables = new Hashtable();

foreach (string s in pairs)
{
string[] keyvp = s.Split("=");

switch (keyvp.Count)
{
case 1:
{
variables.Add(keyvp[0], ""); //if no value is present then add a blank
break;
}
case 2:
{
variables.Add(keyvp[0], keyvp[1]);
break;
}
default:
{
throw new Exception("Bad URL Input");
}
}
}




now you can use that hashtable like so

private void DoSomthing()
{
Console.WriteLine("My language is " + variables["hl].ToString();
}
 
string vars = url.SubString(index, url.Length - index);

- you can omit the second argument (i think)

string vars = url.SubString(index);

;)
 
elhaix,
You posted the same question thread732-1333925 and and we answered it with the code.

If you do not like Dictionary<string><string> use a Hashtable as JurkMonkey suggests.

Marty
 
Works great except for a few minor changes:

int index = url.IndexOf("?");
should be
int index = url.IndexOf("?")-1;

and Split references use a single quote.

Good text parser :). I remember in Java there was the string tokenizer. hmm...


Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top