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)?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Yes, strings are immutable in C#, so it will allocate a new block of memory.
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".

Comments

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);

2 Comments

ToString() generates a copy. So: no.
@Hans Passant Mine was just an example. The StringBuilder class treats strings as mutable, so the manipulation itself is memory efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.