How to remove a part of string effectively

2020-06-08 05:27发布

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?

标签: c# .net
6条回答
Emotional °昔
2楼-- · 2020-06-08 06:00
string xyz = "A=B&C=D&E=F";
string output = xyz.Replace("&C=D","");

Output: A=B&E=F

查看更多
一纸荒年 Trace。
3楼-- · 2020-06-08 06:10
using System.Web; // for HttpUtility

NameValueCollection values = HttpUtility.ParseQueryString("A=B&C=D&E=F");
values.Remove("C");
values.ToString();  // "A=B&E=F"
查看更多
够拽才男人
4楼-- · 2020-06-08 06:13

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

查看更多
霸刀☆藐视天下
5楼-- · 2020-06-08 06:21

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

查看更多
等我变得足够好
6楼-- · 2020-06-08 06:22

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("&");
查看更多
小情绪 Triste *
7楼-- · 2020-06-08 06:24

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.

查看更多
登录 后发表回答