简体   繁体   English

逐字字符串替换

[英]Verbatim string replace

    var a = "asdfgh\r";
    Console.WriteLine(a.Contains(@"\r"));
    var b = a.Replace(@"\r","").Replace(@"\n","");
    var c = a.Replace("\r","").Replace("\n","");
    Console.WriteLine(a);
    Console.WriteLine(b);
    Console.WriteLine(c);

"b" and "c" prints same string and "a" prints false, “b”和“c”打印相同的字符串,“a”打印假,

I was trying to replace \r and \n to an empty char so first i tried below code, there's a backslash in "\r" and "\n" so i decided to use "@" before them;我试图将 \r 和 \n 替换为空字符,所以首先我尝试了下面的代码,“\r”和“\n”中有一个反斜杠,所以我决定在它们之前使用“@”;

var b = a.Replace(@"\r","").Replace(@"\n","")

but this didn't work,但这没有用,

var c = a.Replace("\r","").Replace("\n","");

this works, so im confused when should i use "@" charachter?这行得通,所以我很困惑什么时候应该使用“@”字符?

You declared string a to end with carriagereturn character:您声明字符串a以回车符结尾:

var a = "asdfgh\r"; //it has a length of 7 when compiled 

So you must replace the carriage return with nothing:因此,您必须将回车替换为空:

Replace("\r","")

If you had declared the string to end with "backslash r":如果您已声明字符串以“反斜杠 r”结尾:

var a = @"asdfgh\r"; //it has a length of 8 when compiled 

Then you would have succeeded in replacing "backslash r" with nothing:那么你就可以成功地用任何内容替换“反斜杠 r”:

Replace(@"\r","")

This would also work:这也可以:

Replace("\\r","")

Because the double slash is turned into a single and then the r is a normal character so you're replacing "backslash r" and not carriagereturn因为双斜杠变成了单斜杠,然后 r 是一个普通字符,所以你要替换“反斜杠 r”而不是回车


When compiling the C# compiler looks for \ in a string and converts the following character(s) according to some rule.在编译 C# 时,编译器会在字符串中查找 \ 并根据某些规则转换以下字符。 Using @ before the string turns this off.在字符串之前使用 @ 会关闭此功能。 Mostly it's useful for paths.大多数情况下,它对路径很有用。 Remember that it's a compile time thing, not something you need to do to variables that hold data entered in runtime.请记住,这是编译时的事情,而不是您需要对保存在运行时输入的数据的变量执行的操作。 Putting an @ before a variable name means something different - allowing you to call a variable a reserved word, like string @for = "for" - deplorable practice;在变量名前加上 @ 意味着不同的东西——允许你将变量称为保留字,如string @for = "for" ——可悲的做法; don't do it不要这样做

Ultimately the problem is that you were inconsistent when declaring your strings - a was not a verbatim string so it really did have a single carriage return char, and then you were trying to replace using a verbatim string (and "backslash r" is a different string to "carriagereturn"最终的问题是您在声明字符串时不一致 - a不是逐字字符串,因此它确实有一个回车字符,然后您尝试使用逐字字符串替换(并且“反斜杠 r”是不同的字符串到“回车”

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

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