2

I have a string which has a character I would like to replace.

The character has a hex value of 96 and I would like to replace that character with a hex value of 2D. I tried to do a simple replace on the string but it didn't work because for some reason it doesn't recognize the char. And whenever I print it out it just prints a blank value:

byte testByte = byte.Parse("96", System.Globalization.NumberStyles.HexNumber);
char testChar = Convert.ToChar(testByte);  // when I print this its just a blank char

So, I moved on and converted the entire string into hex, but am not sure how to convert the hex value string back to string. Here's what I have:

// using windows 1252 encoding
System.Text.Encoding windows1252Encoding = System.Text.Encoding.GetEncoding(1252);
byte[] myByte = windows1252Encoding.GetBytes(myString);
var myHexString = BitConverter.ToString(myByte);

myHexString = myHexString .Replace("96", "2D");

so at this point I have replaced the hex value 96 to 2D, but how do I convert this hex value string back to string? Any help would be great!

2
  • What exactly do you mean by "the character has a hex value of 96"? Do you mean it's U+0096? Commented Nov 18, 2013 at 22:43
  • Really? That sounds very odd to me - where has this string come from? It would really help if you'd give more context. Commented Nov 19, 2013 at 0:15

2 Answers 2

2

If you're actually trying to replace U+0096 with U+002D, you can use:

text = text.Replace("\u0096", "\u002d");

Note that U+0096 is "start of guarded area" though. If you actually mean "the value that is encoded in Windows 1252 as 96" then you might want:

text = text.Replace("\u2020", "\u002d");

(Based on the Wikipedia cp 1252 page, which shows 0x96 mapping to U+2020.)

Sign up to request clarification or add additional context in comments.

Comments

0

Just replace one character with the other. You can use the \x escape code to use a character code in hex to specify a character:

s = s.Replace('\x96', '\x2d');

2 Comments

I'd personally recommend using \u instead of \x - the fact that the latter is variable-length make is brittle.
@JonSkeet: That's a good point, and I would understand it used in a string, but a character literal can only contain exactly one character, so the code can't be misinterpreted by the compiler as being something else. In that case you would get a compilation error instead.

Your Answer

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