C# 如何使用indexof和substring从字符串中提取特定文本?

C# 如何使用indexof和substring从字符串中提取特定文本?,c#,.net,C#,.net,我有这个字符串,我使用了子字符串,但它不是我想要的。 我想删除字符串中从索引39开始的部分。 然后从另一个索引开始删除另一个零件。 最后重建字符串 string test = "http://test.com/attachment.php?s=21c4a95ffd0c8110e18a44ace2468fb3&attachmentid=85411&d=1432094822"; test = test.Substring(39); 最后,字符串应该如下所示: 为了安

我有这个字符串,我使用了子字符串,但它不是我想要的。 我想删除字符串中从索引39开始的部分。 然后从另一个索引开始删除另一个零件。 最后重建字符串

string test = "http://test.com/attachment.php?s=21c4a95ffd0c8110e18a44ace2468fb3&attachmentid=85411&d=1432094822";
test = test.Substring(39);
最后,字符串应该如下所示:


为了安全起见,您应该使用
System.Uri
来解析URL

var uri = new System.Uri(HttpUtility.HtmlDecode("http://test.com/attachment.php?s=21c4a95ffd0c8110e18a44ace2468fb3&attachmentid=85411&d=1432094822"));
var leftPart = uri.GetLeftPart(UriPartial.Path);

var queryStringParts = HttpUtility.ParseQueryString(uri.Query);

var uriBuilder = new UriBuilder(leftPart);
uriBuilder.Query = string.Format("attachmentid={0}&d={1}", 
    HttpUtility.UrlEncode(queryStringParts.Get("attachmentid")), 
    HttpUtility.UrlEncode(queryStringParts.Get("d")));

var result = uriBuilder.ToString();

以下是与Daniel类似的方法:

string finalurl = null;
string url = "http://test.com/attachment.php?s=21c4a95ffd0c8110e18a44ace2468fb3&attachmentid=85411&d=1432094822";
Uri uri;
if(Uri.TryCreate(url, UriKind.Absolute, out uri))
{
    var queryString = url.Substring(url.IndexOf('?')).Split('#')[0];
    string decoded = System.Web.HttpUtility.HtmlDecode(queryString);
    var nameVals = System.Web.HttpUtility.ParseQueryString(decoded);
    nameVals.Remove("s"); // remove your undesired parameter
    finalurl = String.Format("{0}{1}{2}{3}?{4}"
            , uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath
            , nameVals.ToString());
}

您需要添加对
System.Web.dll的引用

是否有拆分字符串的模式?它总是
39
字符吗?您熟悉String.Split函数还是如何使用正则表达式。。还有谷歌msdn C#SubString函数或
URI
类我忘了那一个你应该使用
System.URI
来解析URI。你可能想看看。这就像是
字符串.Substring
的倒数。尽管as@DanielA.White说
System.Uri
是这里使用的正确工具。首先看一下类。因为您将对同一字符串进行一些更改。StringBuilder效率更高。为什么要手动执行查询字符串?@DanielA.White:因为我想到了这一点。我已经测试了你的方法后,我已经张贴了这一点,但不幸的是,它没有工作。也许我做错了什么。上面说,
Query
是只读的。是的,这是一个输入错误。@DanielA.White:即使我喜欢你的方法,它似乎也不会给出期望的结果,但是:
http://test.com:80/attachment.php?d=1432094822
。因此不需要端口,并且缺少
attachmentId
参数。您可以通过指定
-1
来删除端口,因此
uriBuilder.port=-1