如何使用 Split() 重构此 C# 代码? [英] How can I refactor this C# code using Split()?
本文介绍了如何使用 Split() 重构此 C# 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何重构它以便 numberOfItems 不必声明为变量?
How can I refactor this so that numberOfItems doesn't have to be declared as a variable?
//method: gets the text in a string in front of a marker, if marker is not there, then return empty string
//example: GetTextAfterMarker("documents/jan/letter043.doc","/") returns "letter043.doc"
//example: GetTextAfterMarker("letter043.doc","/") returns ""
//example: GetTextAfterMarker("letter043.doc",".") returns "doc"
public static string GetTextAfterMarker(string line, string marker)
{
int numberOfItems = line.Split(new string[] { marker }, StringSplitOptions.None).Count();
string result = line.Split(new string[] { marker }, StringSplitOptions.None)[numberOfItems-1];
return line.Equals(result) ? string.Empty : result;
}
推荐答案
如果您使用的是 3.5,这对于 Linq 来说是微不足道的:
If you're using 3.5 this is trivial with Linq:
public static string GetTextAfterMarker2(string line, string marker)
{
string result = line.Split(new string[] { marker }, StringSplitOptions.None).Last();
return line.Equals(result) ? string.Empty : result;
}
这篇关于如何使用 Split() 重构此 C# 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文