当这看起来很简单并且在字符串/字符/正则表达式上有很多问题时,我感到有些愚蠢,但是我找不到我真正需要的东西(除了另一种语言:在特定点后删除所有文本)。
我有以下代码:
[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中删除查询字符串,以便此测试通过?
对于字符串操作,如果只想杀死?之后的所有内容,则可以执行此操作
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句