首先对面试总结一下:
普通的面试经常问到的关于数据结构方面的问题主要包括三类:1) String; 2) Array; 3) List
这三类是最简单的也是使用最频繁的,也因此我们常常忽略了它们的使用。但实际上我们应该加深对这些数据结构的理解。
以String为例说明:
1)使用Split方法分拆字符串;
public static string[] Split2(this string str, params char[] separators)
{
int i = 0;
string sub;
List<string> result = new List<string>();
while (i < str.Count())
{
//Get the min index about all of delimiters
int minIndex=int.MaxValue;
foreach (char ch in separators)
{
int index = str.IndexOf(ch, i);
if (index == -1)
continue;
else if (index < minIndex)
minIndex = index;
}
if (minIndex != int.MaxValue)
{
sub = str.Substring(i, minIndex - i);
result.Add(sub);
}
else
{
sub = str.Substring(i);
result.Add(sub);
break;
}
i = ++minIndex;
}
return result.ToArray();
}
}
自己写一个Split方法来体会。
Test Case1: "a+b++c" delimiter: '+' Expected Result: {"a", "b", "", "c"}
Test Case2: "+a++b" delimiter: '+' Expected Result: {"", "a", "", "b"}
Test Case3: "a+b" delimiter: '-' Expected Result: {"a+b"}
注意一点:如果你在command line arguments中输入"one\ttwo three:four,five six seven"用于debug,制表符\t不能识别。估计是参数解析的问题。
2)搜索字符串(IndexOf, LastIndexOf, StartsWith, EndsWith)
可以思考一下public int String.IndexOf(string value)的实现。
3)使用正则表达式搜索字符串(Regex)