/* URL decoding in Picat. http://rosettacode.org/wiki/URL_decoding """ This task (the reverse of URL encoding) is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Example The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/". """ See: - http://rosettacode.org/wiki/URL_encoding - http://hakank.org/picat/url_encoding.pi This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. % import cp. main => go. go => List = ["http%3A%2F%2Ffoo%20bar%2F", "http%3A%2F%2Fhakank%2Eorg%2Fpicat%2F", "http%3A%2F%2Fpicat%2Dlang%2Eorg%2F", "http%3A%2F%2Fwww%2Eh%E5kan%2Eorg%2F", % not a working URL "This%20is%20a%20plain%20text%20with%20some%20non%2DASCII7%20chars%3A%20H%E5kan%20%E4r%20sn%E4ll%2E" ], foreach(S in List) println(S=url_decode(S)), println(S=url_decode2(S)) end, nl. % recursive version url_decode(S) = URL => url_decode(S,"",URL). url_decode("", URL0, URL) => URL = URL0. url_decode(['%',H1,H2|S],URL0,URL) => C = chr(parse_term("0x" ++ [H1,H2])), url_decode(S,URL0 ++ [C],URL). url_decode([C|S],URL0,URL) => url_decode(S,URL0++[C],URL). % imperative approach url_decode2(S) = URL => URL = "", I = 1, while (I <= S.length) if S[I] == '%' then C = chr(parse_term("0x" ++ [S[I+1],S[I+2]])), I := I + 2 else C = S[I] end, URL := URL ++ [C], I := I + 1 end.