0

I am in a situation where i have to replace some Windows-1252 special characters. More characters may be added later - so i want a general method instead of this hardcoding.

private string URLEncode(string s)
        {
            s = s.Replace("ø", "%f8");
            s = s.Replace("Ø", "%f8");
            s = s.Replace("æ", "%e6");
            s = s.Replace("Æ", "%e6");
            s = s.Replace("å", "%e5");
            s = s.Replace("Å", "%e5");
            return s;
        }

Is this possible? I don't know what this '%f8' format is, but it works.

capcapdk
  • 179
  • 1
  • 15
  • Stuff like this I always make table-driven. You can put all the OriginalChars in one field and the ReplacementChars in another, and then just loop through your table. This way, if you need to add other pairs later, you don't have to touch the code. – Johnny Bones Sep 16 '16 at 15:59
  • That is plan B. However, there must be some method to convert a UTF-8 character into this '%xx' format? – capcapdk Sep 16 '16 at 16:01
  • You can convert to string using following then use winStr.SubString(0,1) to get indivual characters : byte[] input = { 0xf8, 0xe6, 0xe5 }; string winStr = Encoding.GetEncoding(1256).GetString(input); byte[] output = Encoding.GetEncoding(1256).GetBytes(winStr); – jdweng Sep 16 '16 at 16:10

1 Answers1

2

Okay, now I get your problem. I think I found a suitable solution in another post:

UrlEncoding issue for string with ß character

Which in your case could be:

var source = "tØst".ToLowerInvariant();
var encodedUrl = HttpUtility.UrlEncode(source, Encoding.GetEncoding(1252));

I had to make the string lowercase to better match your current mapping.

Community
  • 1
  • 1