有没有人建议如何将一个字符串分割成数组列表,并且数组列表的每个字符串的大小必须小于1mb。
我有字符串变量中提供的字符串值。我需要遍历字符串值,然后检查字符串大小应始终> 1MB,如果大小大于1MB,则拆分字符串数据并将其存储在数组列表的子字符串中。
有人能建议我如何在我下面的代码实现它:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System;
class Program
{
public static void Main()
{
String[][] TextFile = new String[5][] { { "Mike", "Amy" }, { "Mary", "Albert" } } ;
for (int i = 0; i < TextFile.Length; i++)
{
TextFile[i] = new String[i + 1];
}
for (int i = 0; i < TextFile.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, TextFile[i].Length);
}
}
}
您要做的事情有点尴尬。如何获得每个字符的字节计数,然后相应地计算字符串长度?
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
如果你真的想尝试这种方法,这是另一种进行调查的方法。
Encoding.Default.GetBytes("Hello");
CharithJ的回答很好,但只是为了完成。
如果你有尺寸而不是内容的要求,那么我想你不需要单独阅读/修改部分。如果是这种情况,您不需要它们在字符串中,而是一个byte[]就足够了。这样就不需要计算编码字符的大小(甚至不需要知道编码)。您可以将字符串转换为byte[](字节到字节)
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
那么你可以用这个SO问题把它分成小于1 048 576 (1 MB)的部分