将一个数组元素复制到另一个数组 [英] Copying one array element to another array

查看:145
本文介绍了将一个数组元素复制到另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码来逐个字符读取文本框并将这些字符复制到另一个数组中.一旦出现空格字符,该过程应停止.程序在运行时给出了参数null异常.任何解决方案.

这是代码.

I have written a code to read a text box character by character and copy the characters into another array. As soon as the space character occurs the process should stop. the Program is giving argument null exception at runtime. Any solutions.

Here is the code.

Private Sub file_open_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles file_open.Click
Dim objreader As New System.IO.StreamReader(file_name.Text)
    TextBox1.Text = objreader.ReadLine

    TextBox1.Text = TextBox1.Text & objreader.ReadLine & vbCrLf

    Dim myArray() As Char
    Dim myArray2() As Char

    myArray = Me.TextBox1.Text.ToCharArray
    For i As Integer = 1 To 70
        If myArray(i) <> " " Then

        Else
            Array.Copy(myArray, myArray2, i)     'exception here

        End If
    Next

End Sub

推荐答案

您尚未初始化myArray2,因此它为null,就像您的异常告诉您一样.

但是,您发布的代码没有意义,您要做的只是将myArray中的所有元素复制到myArray2中,除了可能在myArray末尾的任何空格.然后您会一次又一次地执行此操作.
you haven''t initialized myArray2 so it''s null just like your exception tells you.

However the code you posted makes no sense, all you''re trying to do is copying all the elements in myArray to myArray2 except any space(s) that might be at the end of myArray. And you''re doing it again and again..


尝试使用字符列表List(Of Char)
并一旦准备好调用ToArray方法.这样,您无需处理数组大小.



Try using a list of chars List(Of Char)
And once ready call ToArray method. In this way you do not need to deal with array sizes.

Something like

Dim myArray1 As List(Of Char) = TextBox1.Text.ToCharArray
Dim myArray2 As List(Of Char) = New List(Of Char)

For Each c As Char In myArray1
    If c <> " " Then
        myArray2.Add(c)
    Else
        Exit For
    End If
Next




干杯




Cheers


这篇关于将一个数组元素复制到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆