我看到了这个question,它询问给定一个字符串"smith;rodgers;McCalne“,您如何生成一个集合。解决这个问题的方法是使用String.Split。
如果我们没有内置Split(),那么您应该做什么呢?
更新:
我承认编写拆分函数相当容易。下面是我会写的。使用IndexOf循环字符串,使用子字符串提取字符串。
string s = "smith;rodgers;McCalne";
string seperator = ";";
int currentPosition = 0;
int lastPosition = 0;
List<string> values = new List<string>();
do
{
currentPosition = s.IndexOf(seperator, currentPosition + 1);
if (currentPosition == -1)
currentPosition = s.Length;
values.Add(s.Substring(lastPosition, currentPosition - lastPosition));
lastPosition = currentPosition+1;
} while (currentPosition < s.Length);我查看了SSCLI实现及其类似于上面的实现,除了它处理更多用例之外,它在进行子字符串提取之前使用一种不安全的方法来确定分隔符的索引。
其他人建议如下。
implementation)
)
是这个吗?
发布于 2010-08-27 22:53:30
编写自己的Split等价物相当简单。
下面是一个简单的例子,尽管实际上您可能希望创建一些重载以获得更大的灵活性。(实际上,您只需要使用框架的内置Split方法!)
string foo = "smith;rodgers;McCalne";
foreach (string bar in foo.Split2(";"))
{
Console.WriteLine(bar);
}
// ...
public static class StringExtensions
{
public static IEnumerable<string> Split2(this string source, string delim)
{
// argument null checking etc omitted for brevity
int oldIndex = 0, newIndex;
while ((newIndex = source.IndexOf(delim, oldIndex)) != -1)
{
yield return source.Substring(oldIndex, newIndex - oldIndex);
oldIndex = newIndex + delim.Length;
}
yield return source.Substring(oldIndex);
}
}发布于 2010-08-27 23:15:20
你做你自己的循环来做分裂。下面是一个使用Aggregate扩展方法的方法。效率不高,因为它在字符串上使用了+=运算符,因此它实际上不应该用作示例,但它可以:
string names = "smith;rodgers;McCalne";
List<string> split = names.Aggregate(new string[] { string.Empty }.ToList(), (s, c) => {
if (c == ';') s.Add(string.Empty); else s[s.Count - 1] += c;
return s;
});发布于 2010-08-27 22:22:33
雷吉斯?
或者只是子字符串。这就是斯普利特在内部所做的
https://stackoverflow.com/questions/3588503
复制相似问题