简体   繁体   English

在字符串中添加斜杠

[英]Add slash to string

I want to replace such string 我想替换这样的字符串

'10001'

into 进入

\'10001\'

The following code doesnt work: 以下代码不起作用:

Console.WriteLine(content);
content.Replace("'", "\\'");
Console.WriteLine(content);

or even this: 甚至这个:

Console.WriteLine(content);
content.Replace("'", "\\\\'");
Console.WriteLine(content);

The value content is exactly the same before and after replace , ie '10001' replace前后的值content完全相同,即'10001'

I'm using VC# 2010 Express. 我正在使用VC#2010 Express。 Thanks for help. 感谢帮助。

You have to write: 您必须写:

content = content.Replace("'", "\\'");

string is an immutable type, which means it can't be modified. string是不可变的类型,这意味着它不能被修改。 Instead the methods like Replace , Insert , etc. always return a new string instance. 相反,诸如ReplaceInsert等之类的方法总是返回一个新的字符串实例。 See here for more information. 有关更多信息, 请参见此处

BTW: if you're using ReSharper (or maybe a similar tool), it will warn you when you call string.Replace() without assigning/using the method's return value. 顺便说一句:如果您使用的是ReSharper(或类似的工具),则在调用string.Replace()时会警告您,而无需分配/使用方法的返回值。

试试这个。

content = content.Replace("'", "\\\\\\\\'");

content = content.Replace("'", "\\'")

do you want to output json string? 您要输出json字符串吗? looks like you are attempting to do that. 看起来您正在尝试这样做。 If that's the case you can json serializer to serialize normal string to json string just like the one that you asked for. 如果是这种情况,您可以json序列化程序将普通字符串序列化为json字符串,就像您要的那样。

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

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