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/
Asked
Active
Viewed 1,702 times
0
-
2Do you have some code that you've tried? – entropic Sep 18 '15 at 01:53
-
You want the HTML hex values for the string, or do you actually want to switch from one encoding to another? – Ron Beyer Sep 18 '15 at 01:56
-
this will do the trick in javascript – Andy Sep 18 '15 at 01:57
-
the html hex values for the string. – Andy Sep 18 '15 at 01: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 Sep 18 '15 at 02:06
-
sorry had a hard time explaining this. I appreciate the help! – Andy Sep 18 '15 at 02:14
3 Answers
3
Try this:
var s = "hi";
var ss = String.Join("", s.Select(c => "&#" + (int)c + ";"));

ycsun
- 1,825
- 1
- 13
- 21
0
Try this:
string myString = "Hi there!";
string encodedString = myString.Aggregate("", (current, c) => current + string.Format("&#{0};", Convert.ToInt32(c)));

Icemanind
- 47,519
- 50
- 171
- 296
-
Fancy, but one should not build long string with string concatenation... If rebuilding `String.Join` with `Enumerable.Aggregate` you should still use `StringBuilder`... – Alexei Levenkov Sep 18 '15 at 02:07
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();
}

Community
- 1
- 1

Mark Feldman
- 15,731
- 3
- 31
- 58