In addition to the other answers, I would like to point out that if the
initial value ever becomes significantly longer (say, 1k) you'll need to
switch to yet another algorithm. The problem with any approach that does
remove/insert is that it's going to be O(n) on the number of characters in
the string (as it has to move the characters around.)
I would encapsulate it in a function as such:
static void ReplaceAt(int startPosition, StringBuilder sb, string
replaceWith)
{
int iLen = replaceWith.Length;
if (sb == null)
{
throw new ArgumentNullException("sb", "Argument cannot be null");
}
if (iLen+startPosition > sb.Length)
{
throw new
ArgumentOutOfRangeException("sb",sb,string.Format( "StringBuilder is not
large enough to support the replacement text '{0}' at the specified starting
position '{1}'.",replaceWith,startPosition));
}
for (int count = 0; count != iLen; count++)
{
sb[count+startPosition] = replaceWith[count];
}
}
I think that should do the trick.
--
Reginald Blue
"I have always wished that my computer would be as easy to use as my
telephone. My wish has come true. I no longer know how to use my
telephone."
- Bjarne Stroustrup (originator of C++) [quoted at the 2003
International Conference on Intelligent User Interfaces]
Matt wrote:
10 len space designated strings grows when i do sb.insert.
is there way to stop string growing. It becomes 14 space len on
test.file
I like to be able insert 3rd position but length should stay 10
string initialValue = " ";
string xyz = "xyz";
sb = new StringBuilder(initialValue);
sb.Insert(3, xyz);
m.Writer("c:/test.txt",sb.ToString());