拆分,最大字符限制的字符串 [英] split a string with max character limit

查看:148
本文介绍了拆分,最大字符限制的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个字符串分解成许多字符串(列表),每一种具有字符的最大限制。所以说,如果我有500个字符的字符串,我想每串有75 A最大,将有7串,最后人会不会有一个完整的75

I'm attempting to split a string into many strings (List) with each one having a maximum limit of characters. So say if I had a string of 500 characters, and I want each string to have a max of 75, there would be 7 strings, and the last one would not have a full 75.

我已经尝试了一些我在计算器中发现的例子,但他们截断'的结果。任何想法?

I've tried some of the examples I have found on stackoverflow, but they 'truncate' the results. Any ideas?

推荐答案

您可以编写自己的扩展方法做这样的事情。

You can write your own extension method to do something like that

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;
        }
    }
}



然后你就可以把它像这样

And then you could call it like this

string temp = new string('@', 500);

string[] array = temp.SplitOnLength(75).ToArray();

foreach (string x in array)
    Console.WriteLine(x);

这篇关于拆分,最大字符限制的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆