简体   繁体   English

C#从末尾删除整个字符串

[英]C# Removing the whole string apart from the end

I want to be able to remove the entire start of a string except for just the end.我希望能够删除字符串的整个开头,除了结尾。 For example:例如:

http://www.website.com/images/a_image.png

That is my url/string.那是我的网址/字符串。 I want to remove most of the first bit of the string so it will end up being.我想删除字符串的大部分第一位,这样它就会结束。

a_image.png

What is the most reliable and efficient way to do this?什么是最可靠和最有效的方法来做到这一点?

Uri myuri = new Uri("http://www.website.com/images/a_image.png
");

String last_part = myuri.Segments[myuri.Segments.Length-1];  

or要么

String last_part = myuri.Segments.Last();

Path.GetFileName will do this for you. Path.GetFileName将为您完成此操作。

Path.GetFileName("http://www.website.com/images/a_image.png");

Returns退货

a_image.png a_image.png

string str="http://www.website.com/images/a_image.png";
str=str.Substring(str.LastIndexOf("/")+1);

Assuming what you want is to get the final part of your URL (ie the value after the last / character), then you can use the String.LastIndexOf(...) method.假设您想要的是获取 URL 的最后一部分(即最后一个/字符之后的值),那么您可以使用String.LastIndexOf(...)方法。 So you could do something like the following:因此,您可以执行以下操作:

string url = @"http://www.website.com/images/a_image.png";

int breakIndex = url.LastIndexOf('/');
string lastFragment = url.Substring(breakIndex + 1);

This will give you the result of "a_image.png".这将为您提供“a_image.png”的结果。

Try尝试

var str = "http://www.website.com/images/a_image.png";
var reqdstr = str.Split('/')[str.Split('/').Count()-1];

Simple way (quite unsafe tho):简单的方法(非常不安全):

string a = "http://www.website.com/images/a_image.png";
string b = a.Remove(0, a.LastIndexOf("/") + 1);

Split the URL string based on forward slash (/) which will return an array containing various components of the URL.根据正斜杠 (/) 拆分 URL 字符串,这将返回一个包含 URL 各种组件的数组。 Use the last index(array.length -1) which will fetch you the image使用最后一个索引(array.length -1),它将为您获取图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM