简体   繁体   中英

how i can shuffle or randomize all words in textfile?

i need to randomize or shuffle all words in textfile.

for example in my textfile i have following words

hello world i have good one
today is good day
it good to see you
all that kind thing world 
boy man women girl 

and after shuffle or randomize i want to get result like this one

is see kind boy today
world all hello women
man that to you day
girl it i one good
have thing world

how i can do in vb.net? thanks in advance


resolved Module Module1

        Sub Main()
            Dim lines() As String = IO.File.ReadAllLines("C:\Users\Username\Desktop\nice.txt")
            Dim outputData As String = RandomizeWords(lines)

            IO.File.WriteAllText("C:\Users\Username\Desktop\nice123.txt", outputData)
            Console.ReadLine()
        End Sub

        Private Function RandomizeWords(lines() As String) As String

            Dim sb As New StringBuilder()
            Dim newList As New List(Of String)

            For Each line In lines
                Dim orderedWords() As String = line.Split(" "c)
                Dim randomizedWords = From n In orderedWords Order By Guid.NewGuid() Select n

                newList.AddRange(randomizedWords)
            Next

            Dim wordCount As Integer = 0

            For i = 0 To newList.Count - 1
                Dim randomIndex As Integer = New Random().Next(0, newList.Count - 1)

                If wordCount = 4 Then
                    sb.AppendLine(newList(randomIndex))
                    wordCount = 0
                Else
                    sb.Append(newList(randomIndex) & " ")
                End If

                newList.RemoveAt(randomIndex)

                wordCount += 1
            Next

            Return sb.ToString()
        End Function
    End Module
  1. Extract each separate word as a string and add it to a string array.

  2. Shuffle your string array.

  3. Print out the words in your array in their new shuffled order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM