字符串分割为具有一定规模的大块 [英] Splitting a string into chunks of a certain size

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

问题描述

假如我有一个字符串:

 字符串str =1111222233334444;

我怎样才能打破这种字符串转换成一些大小的块?

例如,闯入的4种尺寸,这将返回字符串:

 1111
2222
3333
4444


解决方案

 静态的IEnumerable<串GT;斯普利特(字符串str,诠释CHUNKSIZE)
{
    返回Enumerable.Range(0,str.Length / CHUNKSIZE)
        。选择(I => str.Substring(我* CHUNKSIZE,CHUNKSIZE));
}

请注意,额外的code可能需要适当地处理边界情况(或空输入字符串, CHUNKSIZE == 0 ,输入字符串的长度不是由 CHUNKSIZE 等)。原来的问题没有明确规定对这些边缘情况和现实生活的要求可能会有所不同的要求,所以他们是出于这个答案的范围。

Suppose I had a string:

string str = "1111222233334444"; 

How can I break this string into chunks of some size?

e.g., breaking this into sizes of 4 would return strings:

"1111"
"2222"
"3333"
"4444"

解决方案

static IEnumerable<string> Split(string str, int chunkSize)
{
    return Enumerable.Range(0, str.Length / chunkSize)
        .Select(i => str.Substring(i * chunkSize, chunkSize));
}

Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0, input string length not divisible by chunkSize, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.

这篇关于字符串分割为具有一定规模的大块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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