【问题标题】:Using LINQ to strip a suffix from a string if it contains a suffix in a list?如果字符串包含列表中的后缀,则使用 LINQ 从字符串中去除后缀?
【发布时间】:2011-06-12 02:37:35
【问题描述】:

如何使用 C#/LINQ 从字符串中去除后缀并返回它?示例:

string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };

string myString = "DeleteItemMessagePlural";

string stringWithoutSuffix = myString.???; // what do I do here?

// stringWithoutSuffix == "DeleteItemMessage"

【问题讨论】:

  • 后缀是否重叠?是否要删除多个后缀?

标签: c# .net linq string linq-to-objects


【解决方案1】:
var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
    myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));

【讨论】:

  • +1 - 我会做的。或者 newMyString = myString.Remove(myString.Length - suffix.Length)。
  • FirstOrDefault() 如果未找到,将给出 null ,然后在下一行给出 null 异常。理想情况下,如果你想要一个,使用 Single() 它会更快抛出(在更长的示例中可能是一个问题)并且语义更清晰。您也可以将条件放在 Single(...) 中。
  • 你应该检查 null 或者你可以使用.First()。如果没有后缀,您的代码会在前面的一行崩溃,并带有讨厌的NullReferenceException,因为firstMatchingSuffix 为空。
【解决方案2】:

您需要从列表中构建一个正则表达式:

var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");

string stringWithoutSuffix = regex.Replace(myString, "");

【讨论】:

  • 这是“可以”而不是“需要”,不是吗?总是有不止一种方法;)
【解决方案3】:
// Assuming there is exactly one matching suffix (this will check that)
var suffixToStrip = suffixes.Single(x => myString.EndsWith(x));

// Replace the matching one:
var stringWithoutSuffix =  Regex.Replace(myString, "(" +suffixToStrip + ")$", "");

或者,因为你知道匹配后缀的长度:

// Assuming there is exactly one matching suffix (this will check that)
int trim = suffixes.Single(x => myString.EndsWith(x)).Length;

// Remove the matching one:
var stringWithoutSuffix =  myString.Substring(0, myString.Length - trim);

【讨论】:

  • 你需要Regex.EscapesuffixToStrip
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 2014-05-06
  • 2015-03-27
  • 2013-02-20
  • 1970-01-01
相关资源
最近更新 更多