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/
-
2Do you have some code that you've tried?entropic– entropic2015-09-18 01:53:41 +00:00Commented 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?Ron Beyer– Ron Beyer2015-09-18 01:56:57 +00:00Commented 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;} //-->Andy– Andy2015-09-18 01:57:23 +00:00Commented Sep 18, 2015 at 1:57
-
the html hex values for the string.Andy– Andy2015-09-18 01:58:33 +00:00Commented 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).Alexei Levenkov– Alexei Levenkov2015-09-18 02:06:04 +00:00Commented Sep 18, 2015 at 2:06
|
Show 1 more comment
3 Answers
Try this:
var s = "hi";
var ss = String.Join("", s.Select(c => "&#" + (int)c + ";"));
1 Comment
Andy
this works very well and the answer below. I appreciate all your help!
Try this:
string myString = "Hi there!";
string encodedString = myString.Aggregate("", (current, c) => current + string.Format("&#{0};", Convert.ToInt32(c)));
1 Comment
Alexei Levenkov
Fancy, but one should not build long string with string concatenation... If rebuilding
String.Join with Enumerable.Aggregate you should still use StringBuilder...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();
}