I am trying to parse the following to get all characters to the right of the last "/". Can someone help me?
http://www.mydomain.com/abc
would return 'abc'
http://www.mydomain.com/abc/MyOtherFolder/Thg3kd
Would return 'Thg3kd'
Thanks,
Printable View
I am trying to parse the following to get all characters to the right of the last "/". Can someone help me?
http://www.mydomain.com/abc
would return 'abc'
http://www.mydomain.com/abc/MyOtherFolder/Thg3kd
Would return 'Thg3kd'
Thanks,
use the String.LastIndexOf method + String.Substring or the String.Split method and get the last item from the returned array.
string originalString = "http://www.mydomain.com/abc/MyOtherFolder/Thg3kd";
string newString = "";
int length = originalString.Length;
for (int i = 0; i < length; i++)
{
if (originalString[i] == '/')
{
newString = "";
}
else
{
newString = newString + originalString[i];
}
}
Here I'm just using the HTML tags to make the CODE tags visible...
P.S. It's a nice solution - parsing style, but for what the OP wanted to do, I think String.Split() would do fine; don't get me wrong - what you suggested is perfectly valid, and, what's most important, it works, it's just that, in case that there is a lot of this data to be processed, a potential problem could come from the fact that the String class is immutable - every assignment operation creates a new instance which replaces the original instance. This is why, in such cases, it is recommended for the coder to use the StringBuilder class. Also, the speed could be impacted because the indexer returns a char, which must be converted to a string in each iteration.HTML Code:The [CODE][/CODE] tags.
Incidentally, this is an opportunity to write some extensions (.Net 3.x+) to the String class. So you can do more readable things like:
If you write your own extensions you can overcome the short falls of the Substring(..) method (where it requires indices to actually be in the String), which can be confusing and lead to horrible looking code like:Code:String a = "This is some string of characters";
String b = a.Left(4); // This
String c = a.Mid(7, 11); // some string .... character 7 for 11 characters
String d = a.Right(10); // characters
Which crashes if 'a' is less than 10 characters in length. Whereas using an extension method you can choose to return 'up to 10' characters etc.Code:String b = a.Substring(a.Length - 10, 10);
You can use regular expressions:
Code:string s = "http://www.mydomain.com/abc";
Match m = Regex.Match(s, ".*/(.*)$");
string s = m.Groups[1].Value // 0 is whole string