2

I come from C++ background and was wondering whether in C# exist any magic that would let me to do the following:

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

Is there a chance to do it fast (not write all things by hand) and efficient (have one copy of buffer)?

rjeczalik
  • 21
  • 2

3 Answers3

1

Not very clear what is really your char array is in code provided, but... Use String[] ctor overload to construct the string from your char array, and after call replace with desired parameters.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • it's used as (binary / text) file buffer. Suppose you got a really big file, get a piece of it and process the data in a iterative manner. btw calling `string strbuf = new string(buf)` will allocate more memory, it this true? – rjeczalik Aug 05 '11 at 08:38
  • Yes, strings are immutable in C#, so it will allocate a new block of memory. – Tigran Aug 05 '11 at 08:44
1

Since strings are immutable in .NET, the most memory efficient way of manipulating them is by using the StringBuilder class, which internally treats them as mutable.

Here's an example:

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);
Community
  • 1
  • 1
Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
1

If you need to stay with the array (and cannot use something else to start with, e.g. as others suggested a StringBuilder), then no. There is no built in, "zero-copy", way to "replace a (sub-)char-array with another (sub-)char-array in a given char-array".

Christian.K
  • 47,778
  • 10
  • 99
  • 143