user496949
user496949

Reputation: 86075

How to remove a part of string effectively

Have a string like A=B&C=D&E=F, how to remove C=D part and get the string like A=B&E=F?

Upvotes: 23

Views: 76208

Answers (6)

Naive
Naive

Reputation: 395

string xyz = "A=B&C=D&E=F";
string output = xyz.Replace("&C=D","");

Output: A=B&E=F

Upvotes: 1

Femaref
Femaref

Reputation: 61437

Either just replace it away:

input.Replace("&C=D", "");

or use one of the solutions form your previous question, remove it from the data structure and join it back together.

Using my code:

var input = "A=B&C=D&E=F";
var output = input
                .Split(new string[] {"&"}, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Split('=', 2))
                .ToDictionary(d => d[0], d => d[1]);

output.Remove("C");
output.Select(kvp => kvp.Key + "=" + kvp.Value)
      .Aggregate("", (s, t) => s + t + "&").TrimRight("&");

Upvotes: 41

Jimmy
Jimmy

Reputation: 91442

using System.Web; // for HttpUtility

NameValueCollection values = HttpUtility.ParseQueryString("A=B&C=D&E=F");
values.Remove("C");
values.ToString();  // "A=B&E=F"

Upvotes: 3

mike
mike

Reputation: 3166

I think you need to give a clearer example to make sure it's something for the situation, but something like this should do that:

var testString = "A=B&C=D&E=F"
var stringArray = testString.Split('&');
stringArray.Remove("C=D");
var output = String.Join("&", stringArray);

Something like that should work, and should be pretty dynamic

Upvotes: 2

user
user

Reputation: 6947

Split it on the & separator, exclude the C=D part by some mechanism, then join the remaining two? The String class provides the methods you'd need for that, including splitting, joining and substring matching.

Upvotes: 1

stefan
stefan

Reputation: 2886

You can either split() and manually join (depending how the data looks like) or simly use string.Replace(,string.empty)

Upvotes: 1

Related Questions