开发者

Help with String.CopyTo()

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
     Con开发者_如何转开发sole.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


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 );


You should call the ToCharArray() method instead:

Dim strCopy As Char() = strString.ToCharArray()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜