我正在尝试将字符串拆分为多个字符串(List),每个字符串都有一个最大字符数限制.所以说如果我有一个500个字符的字符串,并且我希望每个字符串的最大值为75,则会有7个字符串,最后一个字符串不会有完整的75个字符串.
我已经尝试了一些我在stackoverflow上找到的例子,但他们"截断"了结果.有任何想法吗?
您可以编写自己的扩展方法来执行类似的操作
static class StringExtensions
{
public static IEnumerable<string> SplitOnLength(this string input, int length)
{
int index = 0;
while (index < input.Length)
{
if (index + length < input.Length)
yield return input.Substring(index, length);
else
yield return input.Substring(index);
index += length;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以这样称呼它
string temp = new string('@', 500);
string[] array = temp.SplitOnLength(75).ToArray();
foreach (string x in array)
Console.WriteLine(x);
Run Code Online (Sandbox Code Playgroud)