删除字符串中特定字符后的字符,然后删除子字符串?

当这看起来很简单,有很多关于字符串/字符/正则表达式的问题,但是我找不到我需要的东西(除了在另一种语言: 删除特定点后的所有文本中)时,我觉得发布这个有点傻。

我有以下密码:

[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);


String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}

我尝试了上面问题中的解决方案(希望语法是相同的!)但没有。我想首先删除 queryString,它可以是任意长度,然后删除页面名,它也可以是任意长度。

如何从完整 URL 中删除查询字符串,以使该测试通过?

408618 次浏览

对于字符串操作,如果您只想删除? 之后的所有内容,您可以这样做

string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);

编辑: 如果最后一个斜杠后面的所有内容都是

string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash

另外,由于您使用的是 URL,因此可以像下面这样使用它

System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);

Uri 课通常是操纵 Urls 的最佳选择。

第二个 Hightechrider: 已经为您构建了一个专门的 Url 类。

但是,我还必须指出,PHP 的 replaceAll 对搜索模式使用正则表达式,您可以在。NET-看看 RegEx 类。

您可以使用.NET 的内置方法来删除 QueryString。 即, Request.QueryString.Remove["whatever"];

这里[]中的 随便啦是您想要的 querystring的名称 拿开。

试试这个..。 希望这个能帮上忙。

若要删除特定 char 之前的所有内容,请使用下面的命令。

string1 = string1.Substring(string1.IndexOf('$') + 1);

它的作用是,获取 $char 之前的所有内容并删除它。现在,如果您想删除字符后面的项目,只需将 + 1改为 -1,就可以设置了!

但是对于一个 URL,我会使用内置的.NET 类来实现它。

在第一个 /之前删除所有内容

input = input.Substring(input.IndexOf("/"));

移除第一个 /之后的所有内容

input = input.Substring(0, input.IndexOf("/") + 1);

删除最后一个 /之前的所有内容

input = input.Substring(input.LastIndexOf("/"));

删除最后一个 /之后的所有内容

input = input.Substring(0, input.LastIndexOf("/") + 1);

在指定的字符之后删除字符的一个更简单的解决方案是使用 字符串方法,如下所示:

移除第一个 /之后的所有内容

input = input.Remove(input.IndexOf("/") + 1);

删除最后一个 /之后的所有内容

input = input.Remove(input.LastIndexOf("/") + 1);

Request.QueryString帮助您获得 parameters和包含在 URL中的值

例子

string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();

所以 customername 变量应该等于 Dave

问候

下面是另一个简单的解决方案。下面的代码将返回’|’字符之前的所有内容:

if (path.Contains('|'))
path = path.Split('|')[0];

实际上,您可以想要多少分隔符就有多少分隔符,但是假设您只有一个分隔符,那么以下是如何在“ |”之后得到所有分隔符的方法:

if (path.Contains('|'))
path = path.Split('|')[1];

(我在第二段代码中修改的只是数组的索引。)