[英]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/src
到http://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.