Другой вариант - использовать String.Remove
modifiedText = text.Remove(text.LastIndexOf(separator));
При некоторой проверке ошибок код может быть извлечен в метод расширения, например:
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;
}
}
}
Может использоваться как:
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('/'));
}
}
Выход:
"http://www.ibm.com/test" ==> "http://www.ibm.com"
"hello/test" ==> "hello"
"//" ==> "/"
"SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter"
"" ==> ""
" " ==> " "