将字符串分割成一定大小的块(Splitting a string into chunks of a certain size)

编程入门 行业动态 更新时间:2024-10-25 14:26:41
字符串分割成一定大小的块(Splitting a string into chunks of a certain size)

假设我有一个字符串:

string str = "1111222233334444";

我怎么能把这个字符串分成一些大小的块?

例如,将其分解为4的大小将返回字符串:

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

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

请注意,要正常处理边缘情况可能需要额外的代码( null或空输入字符串, chunkSize == 0 ,输入字符串长度不能被chunkSize等分)等等。 原始问题没有规定对这些边缘情况的任何要求,在现实生活中,要求可能会有所不同,因此它们超出了本答案的范围。

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.

更多推荐

本文发布于:2023-07-22 18:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222298.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   大小   成一定   Splitting   chunks

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!