开发者

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?


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("&");


using System.Web; // for HttpUtility

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


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


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


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.


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

Output: A=B&E=F

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜