How do I randomly select a string from an array in swift?

How would i read words from a text file into an array using redim?

  • How would i modify this code so that i can read the words in a text file (HangmanWords.txt) into an array and randomly select a word from the array to be displayed? i figure this program should use Redim and the program must handle any reasonable number of words in the text file. this is only a hangman helper and not part of the actual hangman game. Option Explicit Option Base 1 Private Sub cmdRead_Click() Dim strWord() As String Dim intRandom As Integer Dim intFileNum As Integer Open "HangmanWords.txt" For Input As #intFileNum Line Input #intFileNum, strWord() intRandom = Int(Rnd * strWord() + 1) lblDisplay.Caption = strWord() End Sub

  • Answer:

    Assuming VB.NET is the language based off your pseudo-code, that's what I wrote it in. I didn't use a string array, I used an arraylist which is an object of the System.Collections namespace. Also, I didn't test this but if it doesn't work, it should get you in the right direction... Imports System.IO Imports System.Collections Public Class Form1 Private Sub cmdRead_Click() Dim strWord As ArrayList = New ArrayList() Dim rand As New Random Dim fs As FileStream = File.OpenRead("FilePath") Dim sr As New StreamReader(fs) Dim fc As String = sr.ReadToEnd fs.Close() Dim _fc() As String = Split(fc, vbCrLf) For Each word As String In _fc strWord.Add(word.ToString()) Next lblDisplay.Caption = strWord(rand.Next(0, strWord.Count - 1)) End Sub End Class

David L at Yahoo! Answers Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.