user3399326
user3399326

Reputation: 973

replace matching special characters pattern from a string

string s = "apple]","[banana...." ;

I need to remove ( "]","[ ) and replace with "," from above string so that the output looks like below:

s = "apple,banana...."

s = s.Replace(@"\]","[\", ",");  //something like this?

Upvotes: 0

Views: 29

Answers (2)

Jason
Jason

Reputation: 305

I assume it is a string[]?

I propose something like this:

    string[] s = {"[apple]","[banana]","[orange]"} ;
    string new_s = "";
    foreach (string ss in s)
    {                
        new_s += ss.Replace("[", "").Replace("]", ",");                
    }

    //handle extra "," at end of string
    new_s = new_s.Remove(new_s.Length-1);

Edit: Disregard, I misunderstood what you were trying to accomplish due to syntactical errors in your string definition.

string s = "apple]","[banana...." ;

should be:

string s = "apple]\",\"[banana....";

Upvotes: 0

Guffa
Guffa

Reputation: 700192

You need to escape the quotation marks in the string. You have tried to escape something, but \ isn't used to escape characters in a @ delimited string.

In a @ delimited string you use "" to escape ":

s = s.Replace(@"]"",""[", ",");

In a regular string you use \" to escape ":

s = s.Replace("]\",\"[", ",");

Upvotes: 1

Related Questions