当这看起来很简单并且关于字符串/字符/正则表达式有大量问题时,我觉得发布这篇文章有点愚蠢,但我找不到我需要的东西(除了另一种语言:删除特定点之后的所有文本 https://stackoverflow.com/questions/2176544/remove-all-text-after-certain-point).
我有以下代码:
[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);
}
我尝试了上面问题中的解决方案(希望语法相同!)但是没有。我想首先删除查询字符串,它可以是任何可变长度,然后删除页面名称,它也可以是任何长度。
如何从完整 URL 中删除查询字符串以使测试通过?
对于字符串操作,如果你只想杀死 ? 之后的所有内容,你可以这样做
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)