2010-12-26 9 views

Odpowiedz

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

lub

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

(edytowane w celu uwzględnienia przypadku, gdy "/" nie istnieje w łańcuchu, jak wspomniano w komentarzach)

+4

... zakładając, że "/" istnieje w ciągu znaków. W przeciwnym razie otrzymasz 'ArgumentOutOfRangeException'. –

+1

Aby uzyskać wydajność, można uruchomić LastIndexOf i sprawdzić, czy wynik wynosi -1, aby sprawdzić, czy łańcuch zawiera znak. W ten sposób przeszukujesz tylko ciągi, zamiast dwukrotnie (Zawiera + LastIndexOf), które mogą być kosztowne w przypadku dużych ciągów. –

+0

Dobra uwaga. Edytowane. –

1

Kolejne opcji jest użycie String.Remove

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

Z jakiś błąd sprawdzania kodu mogą być pozyskiwane na metodę rozszerzenia jak:

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; 
     } 
    } 
} 

To może być używany jak:

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('/')); 
    } 
} 

Wyjście:

"http://www.ibm.com/test" ==> "http://www.ibm.com" 
"hello/test" ==> "hello" 
"//" ==> "/" 
"SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter" 
"" ==> "" 
"  " ==> "  " 
Powiązane problemy