简体   繁体   English

如何有效地删除一部分字符串

[英]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? 将它拆分在&分隔符上,通过某种机制排除C=D部分,然后加入剩下的两个? The String class provides the methods you'd need for that, including splitting, joining and substring matching. String类提供了您需要的方法,包括拆分,连接和子串匹配。

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

Output: A=B&E=F 输出:A = B&E = F.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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