views:

23

answers:

2

Hi

I am facing a problem with String.CopyTo() method.

I am trying to the copy the value from string to char array using String.CopyTo() method.

Here's my code

Dim strString As String = "Hello World!"

Dim strCopy(12) As Char

strString.CopyTo(0, strCopy, 0, 12)

For Each ch As Char In strCopy
     Console.Write(ch)
Next

Can any one point me in the right direction ?

Thanks.

Edit : I get the this error at runtime. ArgumentOutOfRangeException Index and count must refer to a location within the string. Parameter name: sourceIndex

+1  A: 

You should call the ToCharArray() method instead:

Dim strCopy As Char() = strString.ToCharArray()
SLaks
Thanks for the advice, but I need to stick to String.CopyTo() method for some reason : (
Searock
+1  A: 

From the documentation you get ArgumentOutOfRangeException when:

sourceIndex, destinationIndex, or count is negative

-or-

count is greater than the length of the substring from startIndex to the end of this instance

-or-

count is greater than the length of the subarray from destinationIndex to the end of destination

The first case isn't true as these values are zero or positive.

So it must be that the count is too great for the destination array. Rather than hard code the length do something like this:

strSource.CopyTo ( 0, destination, 4, strSource.Length );
ChrisF
The length is not too great. `"Hello World!".Length` is `12`.
SLaks
Thanks for your answer, I found my problem, the main problem was, I used substring method in my program which reduces the size of strString.
Searock