C# 使用C检查字符串是否出现其他字符串并相应更改字符串的有效方法#
我需要一种方法来有效地搜索特定模式的字符串,并根据找到的模式更改字符串。现在,我的解决方案是可行的,但由于圈复杂度很高,我对它一点也不满意。我得到的是这样的:C# 使用C检查字符串是否出现其他字符串并相应更改字符串的有效方法#,c#,string,search,cyclomatic-complexity,C#,String,Search,Cyclomatic Complexity,我需要一种方法来有效地搜索特定模式的字符串,并根据找到的模式更改字符串。现在,我的解决方案是可行的,但由于圈复杂度很高,我对它一点也不满意。我得到的是这样的: foreach (string test in string[] strings) { if (test.Contains("one") { test = ExecuteCodeOne(test); } if (test.Contains("two") { test
foreach (string test in string[] strings)
{
if (test.Contains("one")
{
test = ExecuteCodeOne(test);
}
if (test.Contains("two")
{
test = ExecuteCodeTwo(test);
}
if (test.Contains("three")
{
test = ExecuteCodeThree(test);
}
if (test.Contains("four")
{
test = ExecuteCodeFour(test);
}
if (test.Contains("five")
{
test = ExecuteCodeFive(test);
}
}
每个ExecuteCode方法执行不同的代码,有一个共同点:它们都调用一个版本的test.Replace(“某个值”,“某个其他值”)
。正如你所看到的,这看起来并不理想。我想把它重构成更好的东西。我的问题是:我是否缺少一种设计模式,可以用来降低复杂性,并有望缩短执行时间
编辑:ExecuteCode方法示例:
private static string ExecuteCodeOne(string test)
{
return test.Replace("value1", "newValue1");
}
private static string ExecuteCodeTwo(string test)
{
if (test.Contains("Value2"))
{
test = test.Replace(new Regex(@"Regex1").Match(test).Groups[1].Value, "");
test = test.Replace("Value2", "");
}
else if (test.Contains("Value3"))
test = test.Replace("Value3", "newValue3");
return test;
}
因此,私有方法做的事情大不相同,包括它们自己的检查,但实际上总是导致String.Replace()的形式。因为这都是由许多单个“if”块组成的,所以我认为所有情况都可以同时发生。另一个需要考虑的是,所有的函数都有不同的逻辑,因此很难找到共同的因素来重构。p> 到目前为止,我最好的想法是使用一个包含要匹配的单词和要执行的函数的字典,这将使它(某种程度上)具有可伸缩性,并且代码将更简单:
Dictionary<string, Func<string,string>> myDict = new Dictionary<string, Func<string, string>>()
{
{"one", ExecuteCodeOne },
{"two", ExecuteCodeTwo },
{"three", ExecuteCodeThree },
{"four", ExecuteCodeFour },
{"five", ExecuteCodeFive },
};
Dictionary myDict=newdictionary()
{
{“一”,行政长官},
{“两个”,executecodewo},
{“三”,行政长官},
{“四”,行政长官},
{“五”,执行定义},
};
然后可以循环字典并应用所有案例:
List<string> toReplaceList = new List<string>();
List<string> result = new List<string>();
foreach(string test in toReplaceList)
{
string temp = test;
foreach (KeyValuePair<string, string> kv in myDict)
{
if (temp.Contains(kv.Key))
temp = kv.Value(temp);
}
result.Add(temp);
}
List-to-replaceList=新列表();
列表结果=新列表();
foreach(存储替换列表中的字符串测试)
{
字符串温度=测试;
foreach(myDict中的键值对kv)
{
如果(温度包含(千伏键))
温度=千伏值(温度);
}
结果。添加(温度);
}
不太好,但还是更好。希望有帮助。您能澄清不同的函数(ExecuteCode{number})的作用吗?他们只做一个替换或者做更多的事情?添加了一个编辑!它们总是导致替换,然后返回,但是由于它们自己的检查,字符串可能并不总是被修改。