3

I am looking for a way to split a URL, such as http://aaa/bbb/ccc/ddd/eee.

How do I get "ccc"? Of course it is possible to split it, but it is not interesting.

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Wild Goat
  • 3,509
  • 12
  • 46
  • 87
  • so is there a pattern you want to match? Say the 3rd part of the url? – JaredPar Feb 28 '12 at 15:51
  • 2
    `string answer = "ccc"` Most elegant possible. Now seriously, could you please provide some more information on how to find that element and in what variations your url may be? – Martin Hennings Feb 28 '12 at 15:53
  • 1
    Why should something like splitting a string be "interesting"? Not sure if trolling but making simple things complicated is a great way to drive your peers batty. Read about incidental complexity and take heed. – gordy Feb 28 '12 at 15:54
  • 2
    I wouldn't call it "elegant" as much as I would "proper". The `Uri` class provides sufficient functionality for dealing with, you guessed it, URIs. – Cᴏʀʏ Feb 28 '12 at 15:55
  • Use the `Uri` class: http://msdn.microsoft.com/en-us/library/system.uri.aspx – vulkanino Feb 28 '12 at 15:52

1 Answers1

21
Uri myuri = new Uri("http://aaa/bbb/ccc/ddd/eee");

String str= myuri.Segments[myuri.Segments.Length-3];  

I think this is the most elegant way you can reach by C#.

EDIT:

Actually you can also go with myuri.Segments[2] here, there give same result. Also note that this code returns "ccc/" as result, so if you want to get "ccc" you can go by this(also elegant) way.

String str= myuri.Segments[myuri.Segments.Length-3].TrimEnd('/');  
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
  • +1 can't get much more elegant than that... I just don't understand why you start counting from the end, instead of just taking `myuri.Segments[1]` – Paolo Falabella Feb 28 '12 at 15:55
  • Yes, myuri.Segments[2] is giving same result. I always needed to catch last part of Uri, so it's like an habit :) – Chuck Norris Feb 28 '12 at 16:11
  • If the author really did want `"ccc"` instead of `"ccc/"`, then add `str = str.TrimEnd('/');` to the above code. Or, if you have the `System.Web` assembly referenced, you can do `str = VirtualPathUtility.RemoveTrailingSlash(str);`. – Lance U. Matthews Feb 28 '12 at 16:12
  • 1
    @mesiesta: you're right, it's Segments[2], not Segments[1]. Glancing at the documentation on the MSDN I had not read the bit where it says that Segment[0] is (for whatever reason) always "/" – Paolo Falabella Feb 28 '12 at 20:09