Find and replace ASCII character with a new line
.net, c#, replace, string
Solution
`char.ConvertFromUtf32`, whilst correct, is not the simplest way to read a character based on its ASCII numeric value. (`ConvertFromUtf32` is mainly intended for Unicode code points that lie outside the BMP, which result in surrogate pairs. This is not something you'd encounter in English or most modern languages.) Rather, you should just cast it using `(char)`.
char c = (char)187;
string replaceMe = c.ToString();
You may, of course, define a string with the required character as a literal in your code: `"»"`.
Your `Replace` would then be simplified to:
n.Replace("»", "\n");
Finally, on a technical level, ASCII only covers characters whose value lies in the 0–127 range. Character 187 is not ASCII; however, it corresponds to `»` in ISO 8859-1, Windows-1252, and Unicode, which collectively are by far the most popular encodings in use today.
Edit: I just tested your original code, and found that it actually worked. Are you sure the result remains on one line? It might be an issue with the way the debugger renders strings in single-line view:
Note that the `\r\n` sequences actually do represent newlines, despite being displayed as literals. You can check this from the multi-line display (by clicking on the magnifying glass):
Problem
I am trying to find every occurrence of an ASCII character in a string and replace it with a new line. Here is what I have so far: ``` public string parseText(string inTxt) { //String builder based on the string passed into the method StringBuilder n = new StringBuilder(inTxt); //Convert the ASCII character we're looking for to a string string replaceMe = char.ConvertFromUtf32(187); //Replace all occurences of string with a new line n.Replace(replaceMe, Environment.NewLine); //Convert our StringBuilder to a string and output it return n.ToString(); } ``` This does not add in a new line and the string all remains on one line. I’m not sure what the problem is here. I have tried this as well, but same result: ``` n.Replace(replaceMe, "\n"); ``` Any suggestions?