Remove text from string until it reaches a certain character

后端 未结 4 2092
忘掉有多难
忘掉有多难 2021-01-17 12:26

I\'m having a issue trying to figure out this. I need to \"fix\" some links, here is an example:

  1. www.site.com/link/index.php?REMOVETHISHERE
  2. www.site.c
4条回答
  •  庸人自扰
    2021-01-17 13:08

    Although a properly crafted string operation will work, the more general way to extract partial URI information is to use the System.Uri type which has methods which encapsulate these operations, e.g.

    var uri = new Uri("http://www.site.com/link/index.php?REMOVETHISHERE");
    var part = uri.GetLeftPart(UriPartial.Path);
    

    This will convey the intent of your code more clearly and you'll be re-using a current implementation which is known to work.

    The System.Uri constructor will throw an exception if the string does not represent a valid URI, but you will anyway probably want to invoke some other behavior in your program if an invalid URI has been encountered. To detect an invalid URI you can either catch the exception or use one of the TryCreate() overloads.

提交回复
热议问题