簡體   English   中英

使用 C# 刪除字符串 URL 的最后一部分

[英]Remove the last part of string URL using C#

我需要從http://localhost/sampleprogram/commonfile/data/sample.json這個 URL 訪問一個 json 文件。

但是,默認的 index.html 在http://localhost/sampleprogram/src/index.html

在 C# 代碼中,如何剪切 URL 的最后一部分:

http://localhost/sampleprogram/srchttp://localhost/sampleprogram

任何方法都可以做到這一點?

如果您確切知道要刪除的部分,則以下內容應該可以工作。

string URL = "http://localhost/sampleprogram/src";
string newURl = URL.Remove(URL.IndexOf("/src"));

這將使您無需計算字符數。

如果您正在使用字符串進行處理,則可以通過以下方式將其刪除

string yourURL = "http://localhost/sampleprogram/src";
string newURL = yourURL.Remove(30);
//expected result http://localhost/sampleprogram

這將刪除字符 30 之后的所有字符串。您也可以在“/”處使用拆分功能並刪除最后一個元素

string yourURL = "http://localhost/sampleprogram/src";

// split string 
string[] result = yourURL.Split('/');
result = result.SkipLast(1).ToArray();
string newURL = String.Join('/', result);

最好的

var url = "http://localhost/sampleprogram/src";
var newUrl = url.Substring(0, url.LastIndexOf("/"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM