用 \\ 替换 \ [英] Replacing \ with \\

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

问题描述

我有一个字符串.我想搜索单斜线,然后用\"(双斜线)替换\"(单斜线).

I have a string. I want to search for a single slash and then replace "\" (single slash) with a "\" (double slash).

string Method1(string s) 
{
     string upadtedString = s;
     if (s.Contains("\\"))
     {
      //do nothing
     }
     else if(s.Contains("\"))
     {
          string s1 = "\";
          string s2 = "\\";
          upadtedString.Replace(s1,s2);
          s = upadtedString;
     }
     return s;
 } 

`

推荐答案

您需要转义反斜杠或使用逐字字符串文字,并且还需要了解字符串是不可变的 - Replace 不会改变现有字符串,它返回一个字符串:

You need to escape backslashes or use a verbatim string literal, and also understand that strings are immutable - Replace doesn't change the existing string, it returns a new string:

// Escaping with an extra backslash
updatedString = s.Replace("\\", "\\\\");

// Using a verbatim string literal
updatedString = s.Replace(@"\", @"\\");

有关转义和逐字字符串文字的更多信息,请参阅我的字符串文章.

For more information on escaping and verbatim string literals, see my strings article.

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

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