C# 替换字符串中的反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10752852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:07:21  来源:igfitidea点击:

Replacing backslash in a string

c#.netstring

提问by mezamorphic

I am having a few problems with trying to replace backslashes in a date string on C# .net.

我在尝试替换 C# .net 上的日期字符串中的反斜杠时遇到了一些问题。

So far I am using:

到目前为止,我正在使用:

string.Replace(@"\","-")

but it hasnt done the replacement. Could anyone please help?

但它没有完成更换。有人可以帮忙吗?

采纳答案by Jon

string.Replacedoes not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:

string.Replace不会修改字符串本身,而是返回一个新字符串,您很可能会丢弃该字符串。改为这样做:

myString= myString.Replace(@"\","-");

On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.

附带说明一下,这种操作通常出现在手动处理格式化日期字符串的代码中。大多数情况下,有比这样的事情更好的方法来做你想做的事(这是什么?)。

回答by Nikhil Agrawal

Use it this way.

以这种方式使用它。

oldstring = oldstring.Replace(@"\","-");

Look for String.Replacereturn type.

寻找String.Replace返回类型。

Its a function which returns a corrected string. If it would have simply changed old string then it would had a voidreturn type.

它是一个返回更正字符串的函数。如果它只是简单地改变了旧字符串,那么它就会有一个void返回类型。

回答by ericosg

You could also use:

您还可以使用:

myString = myString.Replace('\', '-'));

but just letting you know, date slashes are usually forward ones /, and not backslashes \.

但只是让您知道,日期斜杠通常是正斜杠/,而不是反斜杠\

回答by ABH

As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.

正如其他人所建议的那样, String.Replace 不会更新原始字符串对象,而是返回一个新字符串。

myString= myString.Replace(@"\","-");

It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links hereand here

理解字符串在 C# 中是不可变的基本上是为了使其线程安全是值得的。有关字符串的更多详细信息以及它们为何不可变,请参阅此处此处的链接

回答by Dhaval

as all of them saying you need to take value back in the variable.

正如他们所有人都说你需要取回变量中的值。

so it should be

所以应该是

 val1= val1.Replace(@"\","-");

Or

或者

 val1= val1.Replace("\","-");

but not only .. below one will not work

但不仅..低于一个将不起作用

 val1.Replace(@"\","-");