我搜索了一个分割字符串的方法,我找到了一个。 现在我的问题是我无法使用它描述的方法。
它会告诉我
不能隐式地将类型'System.Collections.Generic.IEnumerable'转换为'string []'。
提供的方法是:
public static class EnumerableEx
{
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
}
}
}
他怎么说它被使用:
string[] result = "bobjoecat".SplitBy(3); // [bob, joe, cat]
你必须使用ToArray()
方法:
string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat]
您可以隐式将Array
转换为IEnumerable
但不能反之亦然。
请注意,您甚至可以直接修改方法以返回string[]
:
public static class EnumerableEx
{
public static string[] SplitByToArray(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
var arr = new string[(str.Length + chunkLength - 1) / chunkLength];
for (int i = 0, j = 0; i < str.Length; i += chunkLength, j++)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
arr[j] = str.Substring(i, chunkLength);
}
return arr;
}
}
如果不知何故你最终得到这个:IEnumerable<string> things = new[] { "bob", "joe", "cat" };
你可以把它变成像这样的string[]
:string[] myStringArray = things.Select(it => it).ToArray();