string replace on escape characters

假如想象 提交于 2019-12-30 08:14:39

问题


Today I found out that putting strings in a resource file will cause them to be treated as literals, i.e putting "Text for first line \n Text for second line" will cause the escape character itself to become escaped, and so what's stored is "Text for first line \n Text for second line" - and then these come out in the display, instead of my carriage returns and tabs

So what I'd like to do is use string.replace to turn \\ into \ - this doesn't seem to work.

s.Replace("\\\\", "\\"); 

doesn't change the string at all because the string thinks there's only 1 backslash

s.Replace("\\", "");

replaces all the double quotes and leaves me with just n instead of \n

also, using @ and half as many \ chars or the Regex.Replace method give the same result

anyone know of a good way to do this without looping through character by character?


回答1:


Since \n is actually a single character, you cannot acheive this by simply replacing the backslashes in the string. You will need to replace each pair of \ and the following character with the escaped character, like:

s.Replace("\\n", "\n");
s.Replace("\\t", "\t");
etc



回答2:


You'd be better served adjusting the resx files themselves. Line breaks can be entered via two mechanisms: You can edit the resx file as XML (right-click in Solution Explorer, choose "Open As," and choose XML), or you can do it in the designer.

If you do it in the XML, simply hit Enter, backspace to the beginning of the newline you've created, and you're done. You could do this with Search and Replace, as well, though it will be tricky.

If you use the GUI resx editor, holding down SHIFT while pressing ENTER will give you a line break.

You could do the run-time replacement thing, but as you are discovering, it's tricky to get going -- and in my mind constitutes a code smell. (You can also make a performance argument, but that would depend on how often string resources are called and the scale of your app in general.)




回答3:


I'm actually going with John's solution and editing the XML directly as that's the better solution for the project, but codelogic answered the question that was driving me insane.



来源:https://stackoverflow.com/questions/357804/string-replace-on-escape-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!