tùy chọn khác là sử dụng String.Remove
modifiedText = text.Remove(text.LastIndexOf(separator));
Với một số lỗi kiểm tra mã có thể được chiết xuất một phương pháp khuyến nông như:
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;
}
}
}
Nó có thể được sử dụng như:
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('/'));
}
}
Đầu ra:
"http://www.ibm.com/test" ==> "http://www.ibm.com"
"hello/test" ==> "hello"
"//" ==> "/"
"SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter"
"" ==> ""
" " ==> " "
... giả sử rằng '/' tồn tại trong chuỗi. Nếu không, bạn nhận được một 'ArgumentOutOfRangeException'. –
Để thực hiện, bạn có thể chạy LastIndexOf và kiểm tra xem kết quả là -1 để kiểm tra xem chuỗi có chứa ký tự hay không. Bằng cách này bạn chỉ tìm kiếm thông qua các chuỗi, thay vì hai lần (Chứa + LastIndexOf) có thể tốn kém cho các chuỗi lớn. –
Điểm tốt. Đã chỉnh sửa. –