我如何从使用indexof和substring的字符串提取特定的文本

本文关键字:字符串 提取 文本 substring indexof | 更新日期: 2023-09-27 17:50:27

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

string test = "http://test.com/attachment.php?s=21c4a95ffd0c8110e18a44ace2468fb3&attachmentid=85411&d=1432094822";
test = test.Substring(39);

最后的字符串应该是这样的:

http://test.com/attachment.php?attachmentid=85411& d = 1432094822

我如何从使用indexof和substring的字符串提取特定的文本

您应该使用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的引用