0

I need to convert a string i.e. "hi" to & #104;& #105; is there a simple way of doing this? Here is a website that does what I need. http://unicode-table.com/en/tools/encoder/

6
  • 2
    Do you have some code that you've tried? Commented Sep 18, 2015 at 1:53
  • You want the HTML hex values for the string, or do you actually want to switch from one encoding to another? Commented Sep 18, 2015 at 1:56
  • this will do the trick in javascript <!-- function display(){if(document.forms[0].ascii.value != ''){var vText = document.forms[0].ascii.value; var vEncoded = display2(vText); document.forms[0].unicode.value = vEncoded;}} function display2(source){result = '';for (i=0; i<source.length; i++) result += '&#' + source.charCodeAt(i) + ';'; return result;} //--> Commented Sep 18, 2015 at 1:57
  • the html hex values for the string. Commented Sep 18, 2015 at 1:58
  • @Andy you may want to put your code (even in JS) in the post to show what you've tried. (Also converting the JS you've added in comment to C# should be trivial - you may as well explain what problem you've faced when converting). Commented Sep 18, 2015 at 2:06

3 Answers 3

3

Try this:

var s = "hi";
var ss = String.Join("", s.Select(c => "&#" + (int)c + ";"));
Sign up to request clarification or add additional context in comments.

1 Comment

this works very well and the answer below. I appreciate all your help!
0

Try this:

string myString = "Hi there!";
string encodedString = myString.Aggregate("", (current, c) => current + string.Format("&#{0};", Convert.ToInt32(c)));

1 Comment

Fancy, but one should not build long string with string concatenation... If rebuilding String.Join with Enumerable.Aggregate you should still use StringBuilder...
0

Based on the answer to this question:

    static string EncodeNonAsciiCharacters(string value)
    {
        StringBuilder sb = new StringBuilder();
        foreach (char c in value)
        {
            string encodedValue = "&#" + ((int)c).ToString("d4"); // <------- changed
            sb.Append(encodedValue);
        }
        return sb.ToString();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.