J
Jami Bradley
Hi,
I'm looking for an efficient way to do this, because I know it will be heavily used
I have a fixed width string and I need to substitute a substring of characters with new values. I
can do this with 2 substring calls, but it will need to rebuild the string just to write a few
characters.
Here is the simple, but inefficient, version:
string s = "0123456789";
string r = "abc"; // Value to substitute
int Offset = 3; // Starting index of substring to change
int Length = 3; // Length of substring
// Replace a substring with one of equal length, based on offset and length:
Console.WriteLine("Substring: " + s.Substring(Offset, Length)); // Displays "345"
Console.WriteLine("Original: [" + s + "]");
s = s.Substring(0, Offset) + r.PadLeft(3, ' ') + s.Substring(Offset + Length);
Console.WriteLine("Result: [" + s + "]");
This will take the string "0123456789" and replace the characters starting at offset 3 with "abc".
The result is "012abc6789"
I am guaranteeing that the lengths are the same, so in C/C++ I could do something like this with a
memcpy, but that isn't a very friendly way
TIA,
Jami
I'm looking for an efficient way to do this, because I know it will be heavily used

I have a fixed width string and I need to substitute a substring of characters with new values. I
can do this with 2 substring calls, but it will need to rebuild the string just to write a few
characters.
Here is the simple, but inefficient, version:
string s = "0123456789";
string r = "abc"; // Value to substitute
int Offset = 3; // Starting index of substring to change
int Length = 3; // Length of substring
// Replace a substring with one of equal length, based on offset and length:
Console.WriteLine("Substring: " + s.Substring(Offset, Length)); // Displays "345"
Console.WriteLine("Original: [" + s + "]");
s = s.Substring(0, Offset) + r.PadLeft(3, ' ') + s.Substring(Offset + Length);
Console.WriteLine("Result: [" + s + "]");
This will take the string "0123456789" and replace the characters starting at offset 3 with "abc".
The result is "012abc6789"
I am guaranteeing that the lengths are the same, so in C/C++ I could do something like this with a
memcpy, but that isn't a very friendly way

TIA,
Jami