Thursday, October 28, 2010

VB.Net How to take letters from a string and put each into an element of an array?

In order to make a game of hangman I need to be able to take a word (Of any character length -%26gt; I've used the length property to find the length of the word) and put each individual letter into an element of an array.



Trouble is, I'm hopeless ^^;



Can someone please help me and explain what the code is actually doing? It's important that I understand what is happening.



Thanks again!VB.Net How to take letters from a string and put each into an element of an array?
Via the ToCharArray() method, of course.



http://msdn2.microsoft.com/en-us/library鈥?/a>VB.Net How to take letters from a string and put each into an element of an array?
In most languages a string is an array, so there would be no conversion. You could really treat a string as an array in visual basic as well by using the charAt function of the string.



If you really want to write the code, the basic idea goes like this. First, you need to define an array with the size of the length of the string. Then, you loop through the string and set each character to a position in the array.



Dim Word as String

...

Dim Chars as Character(Word.length)

For i as Integer = 0 To Word.length -1

Chars(i) = Word.charAt(i)

Next



I probably have some errors there, but I'm sure you get the idea.
The .Net framework string type allows read-only character access using the [] indexing operator:



String word = ';polygon';;



// user enters p...

char input = 'p';



for (int i = 0; i %26lt; word.Length; i++)

if (word[i] == input)

// show that correct letter was picked

else

// hang that man!



Whoops, that's C#... oh well, close enough, it's the same framework.

No comments:

Post a Comment