【问题标题】:Split a string with size less than 1MB拆分大小小于 1MB 的字符串
【发布时间】:2015-07-31 13:14:46
【问题描述】:

有人可以建议如何将字符串拆分为 arrayLists,条件是 arraylist 的每个字符串大小应小于 1 MB。

我在字符串变量中提供了字符串值。我需要遍历字符串值,然后检查字符串大小是否应始终 > 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); 并将返回值相加,通过使用它并检查总大小是否小于1Mb,你应该没问题
  • 您可能应该定义大小的含义。内存大小?磁盘大小?网络流的大小?如果是最后两个中的任何一个,您还需要定义您的编码。

标签: c# asp.net .net string c#-4.0


【解决方案1】:

您正在尝试做的事情有点尴尬。如何获得每个字符的字节数,然后相应地计算字符串长度。

System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

如果您真的想尝试这种方法,另一种进行调查的方法。

Encoding.Default.GetBytes("Hello");

【讨论】:

    【解决方案2】:

    CharithJ 的回答很好,但只是为了完成。

    如果您有大小而不是内容的要求,那么我想您不需要单独阅读/修改这些部分。如果是这种情况,您不需要将它们放在字符串中,而 byte[] 就足够了。这样您就不需要计算编码字符大小(甚至不需要知道编码)。您可以将字符串转换为 byte[] (byte-to-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;
    }
    

    然后您可以使用this SO question 将其划分为小于 1 048 576 (1 MB) 的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多