0

I want to replace the 2nd last character in the end of my string builder in an easy and efficient way (ie fast speed and less memory). The string will be about 200-300 mb I guess (not sure). How do I do it ? Will the answer change if the input string also has a newline at its end ?

Thanks.

1
  • 4
    Where is this string coming from? If its from a file.. I would suggest that you Seek to the end and replace the character by writing over the top of it. That saves a 300MB string being in memory.. Commented Oct 28, 2013 at 23:31

2 Answers 2

3

You can use StringBuilder.Chars to overwrite a specific char in the StringBuilder:

// For example, replace 'x' into the 2nd to last char
stringBuilder[stringBuilder.Length-2] = 'x';
Sign up to request clarification or add additional context in comments.

Comments

3

StringBuilder uses an array of chars as its backing store. A simple

StringBuilder sb = new StringBuilder() ;
sb.Append( GetSomeEnormousString() ) ;

sb[ sb.Length - 2 ] = '*' ;

should do you.

Outside of any paging involved, it's a direct memory access.

Comments

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.