假设我有一个字符串:
string str = "1111222233334444";
我如何把这个字符串分成一定大小的块?
例如,将它分解为4的大小将返回字符串:
"1111"
"2222"
"3333"
"4444"
假设我有一个字符串:
string str = "1111222233334444";
我如何把这个字符串分成一定大小的块?
例如,将它分解为4的大小将返回字符串:
"1111"
"2222"
"3333"
"4444"
当前回答
从。net 6开始,我们还可以使用Chunk方法:
var result = str
.Chunk(4)
.Select(x => new string(x))
.ToList();
其他回答
static IEnumerable<string> Split(string str, double chunkSize)
{
return Enumerable.Range(0, (int) Math.Ceiling(str.Length/chunkSize))
.Select(i => new string(str
.Skip(i * (int)chunkSize)
.Take((int)chunkSize)
.ToArray()));
}
另一种方法是:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var x = "Hello World";
foreach(var i in x.ChunkString(2)) Console.WriteLine(i);
}
}
public static class Ext{
public static IEnumerable<string> ChunkString(this string val, int chunkSize){
return val.Select((x,i) => new {Index = i, Value = x})
.GroupBy(x => x.Index/chunkSize, x => x.Value)
.Select(x => string.Join("",x));
}
}
简单而简短:
// this means match a space or not a space (anything) up to 4 characters
var lines = Regex.Matches(str, @"[\s\S]{0,4}").Cast<Match>().Select(x => x.Value);
在多芬和康他汀的答案组合中……
static IEnumerable<string> WholeChunks(string str, int chunkSize) {
for (int i = 0; i < str.Length; i += chunkSize)
yield return str.Substring(i, chunkSize);
}
这将适用于所有可以被分割成大量块的字符串,否则将抛出异常。
如果你想支持任意长度的字符串,你可以使用下面的代码:
static IEnumerable<string> ChunksUpto(string str, int maxChunkSize) {
for (int i = 0; i < str.Length; i += maxChunkSize)
yield return str.Substring(i, Math.Min(maxChunkSize, str.Length-i));
}
然而,OP明确表示他不需要这个;它有点长,很难读,稍微慢一点。本着KISS和YAGNI的精神,我选择第一个选项:它可能是最有效的实现,而且非常简短、可读,而且重要的是,它会对不符合规范的输入抛出异常。
static List<string> GetChunks(string value, int chunkLength)
{
var res = new List<string>();
int count = (value.Length / chunkLength) + (value.Length % chunkLength > 0 ? 1 : 0);
Enumerable.Range(0, count).ToList().ForEach(f => res.Add(value.Skip(f * chunkLength).Take(chunkLength).Select(z => z.ToString()).Aggregate((a,b) => a+b)));
return res;
}
demo
我知道这个问题已经有很多年了,但是这里有一个Rx实现。它处理了长度% chunkSize != 0的问题:
public static IEnumerable<string> Chunkify(this string input, int size)
{
if(size < 1)
throw new ArgumentException("size must be greater than 0");
return input.ToCharArray()
.ToObservable()
.Buffer(size)
.Select(x => new string(x.ToArray()))
.ToEnumerable();
}