user3015248
user3015248

Reputation: 89

replace text string in C#

Hi I have a basic mistake because I do not look at is how to fix the code:

string code = 'dsad {"scans": dssadasd';
code = code.Replace('{"scans":','test');

the problem is that it fails due to strange characters in the first replacement

anyone can help me?

pd :

sorry here have the original line and I forget show, as I have to do the same with this line :

code = code.Replace('"(.*?)": {"detected": (.*?), "version": (.*?), "result": (.*?), "update": (.*?)}','test');

Upvotes: 0

Views: 84

Answers (7)

dcastro
dcastro

Reputation: 68670

  1. in your first string, you should:

    • use \ to escape the double quotes inside the string;
    • or prepend the string with @ and escape with ""

       string code = "dsad {\"scans\": dssadasd";
       string code = @"dsad {""scans"": dssadasd";
      
  2. the ' character is used to delimit chars, not strings. You should use " instead.

    code = code.Replace("{\"scans\":","test");
    

Upvotes: 4

Ruben de la Fuente
Ruben de la Fuente

Reputation: 695

You have to scape the strings

string code = "dsad {\"scans\": dssadasd";
code = code.Replace("{\"scans\":","test");

Upvotes: 2

tom.dietrich
tom.dietrich

Reputation: 8347

You need to escape the double quotes.

string code = "dsad {\"scans\": dssadasd";
code = code.Replace("{\"scans\":", "test");

You also need to use double quotes rather than single quotes for strings- single quotes are only for char values in C#.

Upvotes: 0

Babak Naffas
Babak Naffas

Reputation: 12561

You need to escape the double quotes.

string code = "dsad {\"scans\": dssadasd";
code = code.Replace("{\"scans":',"test");

Upvotes: 0

Luc Morin
Luc Morin

Reputation: 5380

Try this instead:

    string code = "dsad {\"scans\": dssadasd";
    code = code.Replace("{\"scans\":", "test");

Cheers

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

That code is not a valid C#. You need to use double-quotes to represent a string and escape the double-quotes inside of the string:

string code = "dsad {\"scans\": dssadasd";
code = code.Replace("{\"scans\":","test");

Upvotes: 0

Luaan
Luaan

Reputation: 63732

That's not compilable C#. Strings are always double-quoted in C#:

string code = "dsad {\"scans\": dssadasd";
code = code.Replace("{\"scans\":", "test");

C# isn't JavaScript :)

Upvotes: 0

Related Questions