删除字符串中特定字符之后的字符,然后删除子字符串? [英] Remove characters after specific character in string, then remove substring?

查看:97
本文介绍了删除字符串中特定字符之后的字符,然后删除子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当这看起来很简单并且在字符串/字符/正则表达式上有很多问题时,我对此发表了愚蠢的评论,但是我找不到我真正需要的东西(除了另一种语言:在特定点之后删除所有文本)。

I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: 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);
    }

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

I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.

如何获取删除查询的信息

How can I get the remove the query string from the full URL such that this test passes?

推荐答案

对于字符串操作,如果只想杀死?之后的所有内容,是否可以通过此测试? ,您可以这样做

For string manipulation, if you just want to kill everything after the ?, you can do this

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

编辑:如果最后一个斜杠之后的所有内容,请执行

If everything after the last slash, do something like

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,所以您可以使用此代码做一些事情

Alternately, since you're working with a URL, you can do something with it like this code

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

这篇关于删除字符串中特定字符之后的字符,然后删除子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆