[Mono-list] Problems with CopyTo, using Contains(...) and inserting a character from one string into another.

Chris Howie cdhowie at gmail.com
Mon Feb 23 04:06:22 EST 2009

On Tue, Jan 27, 2009 at 6:53 AM, PFJ <pjohnson1 at uclan.ac.uk> wrote:
> I'm trying to copy a specific section of a string to another string.
> My code looks like this
> void search(string s)
> string newstring;
> for (int a = 0 ; a < s.Length; ++a)
> {
>  if (a + 1 > s.Length)
>   continue;
>  if (s[a + 1] < 'a')
>   s.CopyTo(a, newstring.ToCharArray(), 0, 1);
>  else
>  {
>   s.CopyTo(a, newstring.ToCharArray(),0, 2);
>   a++;
>  }
> }

I did not look too deeply into the exception you are getting because
this approach is simply wrong.  You are copying the characters into a
new array that you never use again.  In other words, this block of
code would do absolutely nothing but burn CPU cycles even if it did

You probably want to look at the StringBuilder class as well.  It
better encapsulates actions like this and is designed to prevent you
from creating several intermediate String objects (which you don't do
here but are very likely to do if you haven't done this kind of thing

Chris Howie

More information about the Mono-list mailing list