C# - Substring: index and length must refer to a l

2019-01-18 09:40发布

I have a string that looks like

string url = "www.example.com/aaa/bbb.jpg";

"www.example.com/" is 18 fixed in length. I want to get the "aaa/bbb" part from this string (The actual url is not example nor aaa/bbb though, the length may vary)

so here's what I did:

string newString = url.Substring(18, url.Length - 4);

Then I got the exception: index and length must refer to a location within the string. What's wrong with my code and how to fix it? Thanks in advance.

8条回答
淡お忘
2楼-- · 2019-01-18 09:57

You can use padding right.

string url = "www.example.com/aaa/bbb.jpg";
string newString=url.PadRight(4);
string newString = (url.Substring(18, url.Length - 4)).Trim();

Happy Coding!

查看更多
男人必须洒脱
3楼-- · 2019-01-18 10:00

Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.

string newString = url.Substring(18, 7);

If the length of the substring can vary you need to calculate the length.

Something in the direction of (url.Length - 18) - 4 (or url.Length - 22)

In the end it will look something like this

string newString = url.Substring(18, url.Length - 22);
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-18 10:00
string newString = url.Substring(18, (url.LastIndexOf(".") - 18))
查看更多
做个烂人
5楼-- · 2019-01-18 10:03

You need to find the position of the first /, and then calculate the portion you want:

string url = "www.example.com/aaa/bbb.jpg";
int Idx = url.IndexOf("/");
string yourValue = url.Substring(Idx + 1, url.Length - Idx - 4);
查看更多
狗以群分
6楼-- · 2019-01-18 10:05

How about something like this :

string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension =  Path.GetExtension(path_Query);

path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension
查看更多
虎瘦雄心在
7楼-- · 2019-01-18 10:19

Try This:

 int positionOfJPG=url.IndexOf(".jpg");
 string newString = url.Substring(18, url.Length - positionOfJPG);
查看更多
登录 后发表回答