10

While importing data from a flat file, I noticed that some of lines have embedded non breaking spaces (Hex: A0).

I would like to remove these, but the standard string.replace doesn't seem to work and had considered using regex to replace the string but wouldn't know what the regex would search for to remove it.

Rather than converting the whole string to hex and examining that, is there a better way?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Andy Evans
  • 6,997
  • 18
  • 72
  • 118

4 Answers4

25

Why doesn't string.Replace work?

stringVar.Replace((char)0xA0, ' ');
Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
  • The above changes to blank, right? How do you completely remove it? I tried "" and '', but apparently if you have a char on the left of the replace, you have to have a char on the right side. – NealWalters May 18 '12 at 16:58
  • @NealWaters: You need to use the string version of `Replace` with `null` as the second parameter. – Jackson Pope May 28 '12 at 09:44
13
Regex.Replace(input, "\xA0", String.Empty);

This ought to do it.

KeithS
  • 70,210
  • 21
  • 112
  • 164
7

string.Replace does work. Without using RegEx:

stringVar = stringVar.Replace("\xA0", string.Empty);
Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57
3

Would this work for you?

var myNewString = myCurrentString.Replace("\n", string.Empty );
myNewString = myNewString.Replace("\r", string.Empty );

"\n" is ASCII LineFeed, "\r" is Return.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291