根据集合从另一个字符串中提取字符串的最佳方法

时间:2015-03-13 11:41:45

标签: c# string

我有str这是一个字符串,我想检查字符串的最后一部分是否等于其他字符串,下面我手动执行但是假设我有一个数组strin[] keys = {"From", "To", ...}。如果它相等,我想从str中提取(删除)它并将其放在key内。实现这一目标的最佳方法是什么?

string key;
if(str.Substring(str.Length - 4) == "From");{
  key = "From";
  //Do something with key
}
else if (str.Substring(str.Length - 2) == "To") {
  key = "To";
  //Do something with key
}
... //There may be more string to compare with
str = str.Remove(str.Length - key.Length);

2 个答案:

答案 0 :(得分:3)

您可以使用FirstOrDefaultEndsWith。这将为您提供结束的密钥或null。您必须包含using System.Linq才能生效。

string key = keys.FirstOrDefault(k => str.EndsWith(k));
if(key != null)
{
    str = str.Remove(str.Length - key.Length);
}

答案 1 :(得分:1)

使用foreach循环迭代你的键,然后使用EndsWith()来检测并提取Suc'bString:

foreach(string key in keys)
{
    if(str.EndsWith(key))
    {
        int len = str.Length - key.Length;
        result = str.Substring(0, len);
        break;
    }
}