如何删除某个字符最后一次重复后的所有文本

给定任何字符串,我想删除特定字符后的任何字母。

这个字符可能在字符串中多次出现,我只想将它应用于最后一次出现。

所以我们说“/”是字符,这里有一些例子:

http://www.ibm.com/test ==> http://www.ibm.com
你好/测试==>你好

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

要么

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

(编辑以涵盖字符串中不存在’/’的情况,如评论中所述)

另一个选择是使用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 inputValues = new List { @"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" "" ==> "" " " ==> " "