2010-12-26 10 views

risposta

28
if (text.Contains('/')) 
    text = text.Substring(0, text.LastIndexOf('/')); 

o

var pos = text.LastIndexOf('/'); 
if (pos >= 0) 
    text = text.Substring(0, pos); 

(modificato per coprire il caso quando '/' non esiste nella stringa, come menzionato nei commenti)

+4

... assumendo che '/' esista nella stringa. Altrimenti ottieni un 'ArgumentOutOfRangeException'. –

+1

Per prestazioni, è possibile eseguire LastIndexOf e verificare se il risultato è -1 per verificare se la stringa contiene il carattere. In questo modo si effettua una ricerca solo attraverso le stringhe anziché due (Contains + LastIndexOf) che può risultare costoso per le stringhe di grandi dimensioni. –

+0

Buon punto. Modificato. –

1

Un'altra possibilità è quella di utilizzare String.Remove

modifiedText = text.Remove(text.LastIndexOf(separator)); 

Con qualche errore controllando il codice può essere estratto per un metodo di estensione come:

public static class StringExtensions 
{ 
    public static string RemoveTextAfterLastChar(this string text, char c) 
    { 
     int lastIndexOfSeparator; 

     if (!String.IsNullOrEmpty(text) && 
      ((lastIndexOfSeparator = text.LastIndexOf(c)) > -1)) 
     { 

      return text.Remove(lastIndexOfSeparator); 
     } 
     else 
     { 
      return text; 
     } 
    } 
} 

Potrebbe essere usato come:

private static void Main(string[] args) 
{ 
    List<string> inputValues = new List<string> 
    { 
     @"http://www.ibm.com/test", 
     "hello/test", 
     "//", 
     "SomethingElseWithoutDelimiter", 
     null, 
     "  ", //spaces 
    }; 

    foreach (var str in inputValues) 
    { 
     Console.WriteLine("\"{0}\" ==> \"{1}\"", str, str.RemoveTextAfterLastChar('/')); 
    } 
} 

Uscita:

"http://www.ibm.com/test" ==> "http://www.ibm.com" 
"hello/test" ==> "hello" 
"//" ==> "/" 
"SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter" 
"" ==> "" 
"  " ==> "  " 
Problemi correlati