【问题标题】:Replace all occurrences of a string in given char/byte array in C#在 C# 中替换给定字符/字节数组中所有出现的字符串
【发布时间】:2011-10-20 16:07:40
【问题描述】:

我来自 C++ 背景,想知道在 C# 中是否存在任何可以让我执行以下操作的魔法:

char[] buf = new char[128*1024*1024];
// filling the arr
buf = buf.ToString().Replace(oldstring, newstring).ToArray();

是否有机会快速(不是手动编写所有内容)和高效(拥有一份缓冲区)?

【问题讨论】:

    标签: c# arrays string replace char


    【解决方案1】:

    不太清楚真正您的字符数组在提供的代码中是什么,但是... 使用 String[] ctor overload 从您的 char 数组构造字符串,并在调用后替换为所需的参数。

    【讨论】:

    • 它用作(二进制/文本)文件缓冲区。假设您有一个非常大的文件,获取其中的一部分并以迭代方式处理数据。顺便说一句,调用string strbuf = new string(buf) 会分配更多内存,这是真的吗?
    • 是的,字符串在 C# 中是不可变的,所以它会分配一个新的内存块。
    【解决方案2】:

    由于字符串在 .NET 中是不可变的,因此处理它们的最节省内存的方法是使用 StringBuilderwhich internally treats them as mutable

    这是一个例子:

    var buffer = new StringBuilder(128*1024*1024);
    
    // Fill the buffer using the 'StringBuilder.Append' method.
    // Examples:
    // buffer.Append('E');
    // buffer.Append("foo");
    // buffer.Append(new char[] { 'A', 'w', 'e', 's', 'o', 'm', 'e' });
    // Alternatively you can access the elements of the underlying char array directly
    // through 'StringBuilder.Chars' indexer.
    // Example:
    // buffer.Chars[9] = 'E';
    
    buffer = buffer.Replace(oldstring, newstring);
    

    【讨论】:

    • ToString() 生成一个副本。所以:没有。
    • @Hans Passant Mine 只是一个例子。 StringBuilder 类将字符串视为可变的,因此操作本身具有内存效率。
    【解决方案3】:

    如果您需要留在数组中(并且不能使用其他东西开始,例如其他人建议使用StringBuilder),那么不需要。没有内置的“零复制”方式来“用给定的字符数组中的另一个(子)字符数组替换(子)字符数组”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2022-11-21
      • 2020-02-25
      • 2011-02-23
      • 1970-01-01
      相关资源
      最近更新 更多