字符串替换转义字符 [英] string replace on escape characters

查看:199
本文介绍了字符串替换转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我发现把字符串资源文件将导致他们被视为文字,即把为第一行文字\\\
为第二行文本将导致转义字符本身成为逃脱,等什么是存储的第一行文字\\\
为第二行文字 - 然后将这些在显示出来的,而不是我的回车和标签



那么什么我想要做的是使用与string.replace把 \\ \ - 这并未 :T似乎工作

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



,因为字符串认为有只1反斜杠



<$ P $不改变串在所有p> s.Replace(\\,​​);

替换所有的双引号,并给我留下了仅仅局限于N,而不是\ ñ



此外,使用 @ 和一半的 \ 字符或 Regex.Replace 方法产生相同的结果。



任何人都知道的一个好办法做到这一点未经字符通过字符的循环?


解决方案

由于 \\\
是其实一个字符,你不能简单地将字符串替换反斜线达致这。您将需要转义字符替换每一对 \ 和下面的字符,如:

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


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?

解决方案

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

这篇关于字符串替换转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆