AndrewC
AndrewC

Reputation: 6730

Convert ASCII hex codes to character in "mixed" string

Is there a method, or a way to convert a string with a mix of characters and ASCII hex codes to a string of just characters?

e.g. if I give it the input Hello\x26\x2347\x3bWorld it will return Hello/World?

Thanks

Upvotes: 0

Views: 2978

Answers (2)

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

Quick and dirty:

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"\\x[0-9]{2}");
        string s = @"Hello\x26\x2347World";
        var matches = regex.Matches(s);
        foreach(Match match in matches)
        {
            s = s.Replace(match.Value, ((char)Convert.ToByte(match.Value.Replace(@"\x", ""), 16)).ToString());
        }
        Console.WriteLine(s);
        Console.Read();
    }

And use HttpUtility.HtmlDecode to decode the resulting string.

Upvotes: 3

Hans Olsson
Hans Olsson

Reputation: 54999

I'm not sure about those specific character codes but you might be able to do some kind of regex to find all the character codes and convert only them. Though if the character codes can be varying lengths it might be difficult to make sure that they don't get mixed up with any normal numbers/digits in the string.

Upvotes: 1

Related Questions