Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 基于集合从另一个字符串提取字符串的最佳方法_C#_String - Fatal编程技术网

C# 基于集合从另一个字符串提取字符串的最佳方法

C# 基于集合从另一个字符串提取字符串的最佳方法,c#,string,C#,String,我有str这是一个字符串,我想检查字符串的最后一部分是否等于其他字符串,下面我手动执行,但假设我有一个数组strin[]keys={“From”,“to”,…}。如果它相等,我想从str中提取(删除)它,并将其放入键中。实现这一目标的最佳方式是什么 string key; if(str.Substring(str.Length - 4) == "From");{ key = "From"; //Do something with key } else if (str.Substring(

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

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);

您只需使用
FirstOrDefault
EndsWith
。这将为您提供以其结尾的键或
null
。您必须使用System.Linq包含
,才能使其正常工作

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

您只需使用
FirstOrDefault
EndsWith
。这将为您提供以其结尾的键或
null
。您必须使用System.Linq包含
,才能使其正常工作

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

使用foreach循环迭代密钥,然后使用EndsWith()检测并成功提取:

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

使用foreach循环迭代密钥,然后使用EndsWith()检测并成功提取:

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

数组有一个
。Contains
方法。首先,您应该开始使用,这使您的
子字符串
调用更容易和更可读。@Dan-o如果
包含
我不感兴趣,如果
以某些结尾
,我就感兴趣string@schnaader好的一点我不知道Functionarray有一个
。Contains
方法。首先,你应该开始使用,这使您的
子字符串
调用更容易和更可读。@Dan-o如果
包含
我不感兴趣,如果
以某些结尾
,我就感兴趣string@schnaader很好,我不知道这个函数