Question

I have a string like Fee&#108 and I want to decode it to its ascii representation - feel.
Is there any library in C# that does it, or I have to do it manually?

Was it helpful?

Solution

To decode the string, use WebUtility.HtmlDecode.

Here's a sample LINQPad program that demonstrates:

void Main()
{
    string s = "Feel";
    string decoded = WebUtility.HtmlDecode(s);
    decoded.Dump();
}

Output:

Feel

Note: You're missing a semicolon from the string you've presented in the question. Without the final semicolon, the output will be:

Fee&#108

OTHER TIPS

You can use the following code, here's a console sample:

using System;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication
{
    class Program
    {
        public static String ReplaceASCIICodesWithUTF(String target)
        {
            Regex codeSequence = new Regex(@"&#[0-9]{1,3};");
            MatchCollection matches = codeSequence.Matches(target);
            StringBuilder resultStringBuilder = new StringBuilder(target);
            foreach (Match match in matches)
            {
                String matchedCodeExpression = match.Value;
                String matchedCode = matchedCodeExpression.Substring(2, matchedCodeExpression.Length - 3);
                Byte resultCode = Byte.Parse(matchedCode);
                resultStringBuilder.Replace(matchedCodeExpression, ((Char)resultCode).ToString());
            }
            return resultStringBuilder.ToString();
        }

        static void Main(string[] args)
        {
            String rawData = "Feel";
            Console.WriteLine(ReplaceASCIICodesWithUTF(rawData));
        }
    }
}

To decode:

HttpUtility.HtmlDecode

then, for example,

ASCIIEncoding

GetBytes/GetString (getbytes on decoded string, then getstring from those bytes)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top