文字列内の特定の文字の後の文字を削除し、次に部分文字列を削除しますか? 質問する

文字列内の特定の文字の後の文字を削除し、次に部分文字列を削除しますか? 質問する

これはかなり単純なようで、文字列/文字/正規表現に関する質問がたくさんあるのに、これを投稿するのはちょっとバカげている気がしますが、必要なものを見つけることができませんでした(別の言語を除いて:特定のポイント以降のテキストをすべて削除)。

次のコードがあります:

[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 からクエリ文字列を削除するにはどうすればよいですか?

ベストアンサー1

文字列操作では、? の後のすべてを削除したい場合は、次のようにします。

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);

おすすめ記事