4

I am trying to convert an array of characters into a string array (where each character becomes a string), as I need it to be a string array for some processing on the array later in the program. Here is the code I am using:

Dim inputexpression As String = UCase(txtInput.Text)
Dim arrinputexpressionchar() As Char = inputexpression.ToCharArray()
Dim arrinputexpression() As String

For i = 0 To arrinputexpressionchar.Length
    arrinputexpression(i) = Char.ToString(arrinputexpressionchar(i))
Next

However, this throws up a 'NullReferenceException was unhandled' (Object reference was not set to an instance of an object) error. Why does this code not work?

2
  • Does the error state on which line the error occurs? Commented Oct 28, 2013 at 15:16
  • You don't need i += 1 in a For loop. Commented Oct 28, 2013 at 16:07

1 Answer 1

5

You have declared but not initialized the string array.

You could use LINQ:

Dim charsAsStringArray = inputexpression.
    Select(Function(c) c.ToString()).
    ToArray()

Here's the non-linq way:

Dim strArray(inputexpression.Length - 1) As String
For i = 0 To charArray.Length - 1
    strArray(i) = inputexpression(i).ToString()
Next
Sign up to request clarification or add additional context in comments.

4 Comments

What's the need for the first line? inputexpression(index) should be sufficient?
What first line? The first code snippet has just one line and the second("non-Linq") has this first line: Dim charArray = inputexpression.ToCharArray().
Dim charArray = inputexpression.ToCharArray() but also Dim charsAsStringArray = inputexpression.ToCharArray(). Why do you use .ToCharArray if you could simply use inputexpression.Select() because the String is already treated as Array of Char then?
@igrimpe: good point, edited my answer. That was just a copy-paste issue. Thanks.

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.