Search code examples
c#asp.netstring.net-2.0

String manipulation complexity


I have been programming for one year and I have done string manipulation many times but never understood how it actually works or what the best way of doing it.

Let's say I have this string

String abc = "https://uu2020.devuueva.com/portal/mesddsa/usforeer/nance/tings/M3C102d4104/1007/tingjack/default.aspx";

I want to only this part

"https://uu2020.devuueva.com/portal/mesddsa/usforeer/nance/tings/M3C102d4104"

Characters/Names can change and are dynamic, however "/" isn't. Can someone demonstrate the simplest and the best way of doing it.


Solution

  • One thing to bear in mind here, is that if you're dealing with a Uri, you are better off using the Uri class to extract pieces of information than trying to string-mash a solution together.

    http://msdn.microsoft.com/en-us/library/system.uri.aspx

    For example:

    var part = String.Format("{0}://{1}{2}",uri.Scheme,uri.Authority, String.Join("",uri.Segments.Take(7)));
    

    Gets the section you're after. Live example: http://rextester.com/JRWKOG58567


    EDIT

    Having discovered some more requirement, and frameework limitation, you might be better string mashing this after all, but you can still leverage some functionality from the Uri class.

    var input = "https://uu2020.devuueva.com/portal/mesddsa/usforeer/nance/tings/M3C102d4104/1007/tingjack/default.aspx";
    var uri = new Uri(input);
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("{0}://{1}/",uri.Scheme,uri.Authority);
    
    var parts = uri.PathAndQuery.Split(new char[]{'/'},StringSplitOptions.RemoveEmptyEntries);
    for(var i=0;i<6;i++){
        sb.AppendFormat("/{0}",parts[i])   ;
    }
    Console.WriteLine(sb.ToString());
    

    Live example: http://rextester.com/HBK80648