简体   繁体   English

字符串替换转义字符

[英]string replace on escape characters

Today I found out that putting strings in a resource file will cause them to be treated as literals, ie 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 今天我发现将字符串放在资源文件中将导致它们被视为文字,即将“第一行文本\\ n第二行文本”放入将导致转义字符本身被转义,因此存储的是“第一行的文字\\ n第二行的文字“ - 然后这些出现在显示中,而不是我的回车和标签

So what I'd like to do is use string.replace to turn \\\\ into \\ - this doesn't seem to work. 所以我想做的是使用string.replace将\\\\转换为\\ - 这似乎不起作用。

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

doesn't change the string at all because the string thinks there's only 1 backslash 根本不会改变字符串,因为字符串认为只有1个反斜杠

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

replaces all the double quotes and leaves me with just n instead of \\n 替换所有的双引号,只留下n代替\\ n

also, using @ and half as many \\ chars or the Regex.Replace method give the same result 另外,使用@和一半的\\ chars或Regex.Replace方法给出相同的结果

anyone know of a good way to do this without looping through character by character? 任何人都知道一个很好的方法来做到这一点,而不是逐字逐句地循环?

Since \\n is actually a single character, you cannot acheive this by simply replacing the backslashes in the string. 由于\\n实际上是单个字符,因此只需替换字符串中的反斜杠即可实现此功能。 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

You'd be better served adjusting the resx files themselves. 调整resx文件本身会更好。 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. 可以通过两种机制输入换行符:您可以将resx文件编辑为XML(在解决方案资源管理器中右键单击,选择“打开方式”,然后选择XML),或者您可以在设计器中执行此操作。

If you do it in the XML, simply hit Enter, backspace to the beginning of the newline you've created, and you're done. 如果你在XML中执行它,只需按Enter键,退格到你创建的换行符的开头,然后就完成了。 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. 如果您使用GUI resx编辑器,按住ENTER键的同时按住SHIFT将为您提供换行符。

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.) (您也可以创建性能参数,但这取决于字符串资源的调用频率和应用程序的规模。)

我实际上正在使用John的解决方案并直接编辑XML,因为这是项目的更好解决方案,但是codelogic回答了让我疯狂的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM