简体   繁体   中英

How to remove a part of string effectively

有一个像A = B&C = D&E = F的字符串,如何删除C = D部分并得到像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

你可以split()和手动连接(取决于数据的样子)或者simly使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM