假设我有一个字符串:
string str = "1111222233334444";
我如何把这个字符串分成一定大小的块?
例如,将它分解为4的大小将返回字符串:
"1111"
"2222"
"3333"
"4444"
假设我有一个字符串:
string str = "1111222233334444";
我如何把这个字符串分成一定大小的块?
例如,将它分解为4的大小将返回字符串:
"1111"
"2222"
"3333"
"4444"
当前回答
它不是很漂亮,也不是很快,但它是有效的,它是一行程序,它是LINQy:
List<string> a = text.Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList();
其他回答
修改(现在它接受任何非空字符串和任何正chunkSize) Konstantin Spirin的解决方案:
public static IEnumerable<String> Split(String value, int chunkSize) {
if (null == value)
throw new ArgumentNullException("value");
else if (chunkSize <= 0)
throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");
return Enumerable
.Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
.Select(index => (index + 1) * chunkSize < value.Length
? value.Substring(index * chunkSize, chunkSize)
: value.Substring(index * chunkSize));
}
测试:
String source = @"ABCDEF";
// "ABCD,EF"
String test1 = String.Join(",", Split(source, 4));
// "AB,CD,EF"
String test2 = String.Join(",", Split(source, 2));
// "ABCDEF"
String test3 = String.Join(",", Split(source, 123));
public static List<string> SplitByMaxLength(this string str)
{
List<string> splitString = new List<string>();
for (int index = 0; index < str.Length; index += MaxLength)
{
splitString.Add(str.Substring(index, Math.Min(MaxLength, str.Length - index)));
}
return splitString;
}
从。net 6开始,我们还可以使用Chunk方法:
var result = str
.Chunk(4)
.Select(x => new string(x))
.ToList();
这样写一行代码怎么样?
List<string> result = new List<string>(Regex.Split(target, @"(?<=\G.{4})", RegexOptions.Singleline));
对于这个正则表达式,最后一个块是否小于4个字符并不重要,因为它只查看它后面的字符。
我知道这不是最有效的解决方案,但我不得不把它扔出去。
for (int i = 0; i <= Convert.ToInt32(Math.Truncate(Convert.ToDecimal(_string.Length / _chunkSize))); i++)
{
var _currentChunk = _string.Substring(i * _chunkSize, Math.Min(_chunkSize, _string.Length - i * _chunkSize));
//do something with current chunk
}