Tutorial :How to cut a string


I have a strings like "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben"

And I need only "175_Jahre_STAEDTLER_Faszination_Schreiben" where "root" is separator. How can I do this?


"/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben".Split("/root/")[1] should give you "175_Jahre_STAEDTLER_Faszination_Schreiben"


Another method:

String newstring = file_path.Substring(file_path.LastIndexOf('/') + 1);  


Check out the System.IO.Path methods - not quite files and folders but with the / delimiter it just might work!


If you're looking to extract a part of a string based on an overall pattern, regular expressions can be a good alternative in some situations.

string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";  Regex re = new Regex(@"/root/(?<goodPart>\w+)$");  Match m = re.Match(s);  if (m.Success) {      return m.Groups["goodPart"].ToString();  }  


string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";  string separator = "root";  string slash = "/";  int idx = s.IndexOf(separator);  string result = s.SubString(idx + separator.Length + slash.Length);  


Use String.Split to separate the string with "root" as the separator. Then use the second element of the resulting array.


If you need to find a relative path based on a base path (which it sounds like what the problem you are trying to solve is, or at least a generalization of your problem) you can use the System.Uri class. It does have it's limitations, however. The cleanest and most correct way to find a relative path is to use DirectoryInfo. With DirectoryInfo you can "walk" the directory tree (backwards or forwards) and build a hierarchy based on that. Then just do a little set manipulation to filter out duplicates and what you have left is your relative path. There are some details, like adding ellipses in the correct place, etc..., but DirectoryInfo is a good place to start in order to parse paths based on the current OS platform.

FYI - I just finished writing a component here at work to do just that so it's fairly fresh in my mind.


string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";  int li = s.LastIndexOf("root/");  s = s.Substring(li + 5, s.Length - 1 - (li + 4));  MessageBox.Show(s);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »