Remove text from string until it reaches a certain character

后端 未结 4 2030
忘掉有多难
忘掉有多难 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 12:49
     string s = @"www.site.com/link/index.php?REMOVETHISHERE";
     s = s.Remove( s.LastIndexOf('?') );
     //Now s will be simply "www.site.com/link/index.php"
    

    should do it

    0 讨论(0)
  • 2021-01-17 12:54

    Use string.split.

    string URL = "www.site.com/link/index.php?REMOVETHISHERE"
    var parts = URL.Split('?');
    

    Then parts[0] will contain "www.site.com/link/index.php" and parts[1] will contain "REMOVETHISHERE". You can then use which ever part you want.

    You should add checks to make sure that there are two parts before trying to access the 2nd element of the array. You could (for example) check that the string contains "?" before trying to call Split.

    0 讨论(0)
  • 2021-01-17 13:00

    To remove last "?" and everything after it:

        string input = @"www.site.com/link/index.php?REMOVETHISHERE";
        input = input.Remove(input.LastIndexOf('?'));
    
        OR
    
        string input = @"www.site.com/link/index.php?REMOVETHISHERE";
        input = input.Substring(0, input.LastIndexOf('?'));
    

    Now the output will be:

    www.site.com/link/index.php
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题