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"
"" ==> ""
" " ==> " "
... assumendo che '/' esista nella stringa. Altrimenti ottieni un 'ArgumentOutOfRangeException'. –
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. –
Buon punto. Modificato. –