当这看起来很简单,而且有很多关于字符串/字符/正则表达式的问题,但我找不到我需要的东西(除了另一种语言: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);
    }

我try 了上述问题的解决方案(希望语法相同!)但是没有.我想先删除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);

.net相关问答推荐

获取Ef-Core集合的DeleteBehavior

Msbuild try 构建 msbuild.exe 而不是我的 .csproj 文件

如何使用 awslocal 通过 localstack 中的 cloudwatch events/eventbridge 触发 lambda

无法加载文件或程序集 Microsoft.Extensions.DependencyInjection.Abstractions,版本 = 1.1.0.0

如何判断 IOException 是否为 Not-Enough-Disk-Space-Exception 类型?

每 X 秒执行一次指定函数

您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么?

一种消耗(所有字节)BinaryReader 的优雅方式?

如何将字符串列表数据绑定到 WPF/WP7 中的 ListBox?

.NET 世界是否有 Maven 替代方案或端口?

返回 IQueryable 或不返回 IQueryable

我应该从 .NET 中的 Exception 或 ApplicationException 派生自定义异常吗?

Linq查询分组并 Select 第一个项目

日期时间是什么意思?在 C# 中是什么意思?

如何允许程序集(单元测试)访问另一个程序集的内部属性?

如何在 WebBrowser 控件中注入 Javascript?

为什么发布和调试模式下的代码行为不同?

EF Core 添加迁移构建失败

多行 C# 插值字符串文字

Linq Query 不断抛出无法创建 System.Object 类型的常量值......,为什么?