Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to replace a random word in a string with a random word from a list of words using VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module Program

    Function ReplaceRandomWord(text As String, replacementWords As List(Of String)) As String
        Dim words As New List(Of String)(text.Split(" "c))

        If words.Count = 0 OrElse replacementWords.Count = 0 Then
            Return text   ' nothing to do
        End If

        Dim rnd As New Random()

        ' Pick random index in the sentence
        Dim idx As Integer = rnd.Next(words.Count)

        ' Pick random replacement word
        Dim newWord As String = replacementWords(rnd.Next(replacementWords.Count))

        ' Replace it
        words(idx) = newWord

        ' Rebuild the string
        Return String.Join(" ", words)
    End Function

    Sub Main()
        Dim text As String = "The quick brown fox jumps over the lazy dog"
        Dim replacementWords As New List(Of String) From {"c#", "c++", "java", "rust", "python"}

        Dim result As String = ReplaceRandomWord(text, replacementWords)
        Console.WriteLine(result)
    End Sub

End Module



' run:
'
'  The quick brown fox java over the lazy dog
'

 



answered 6 hours ago by avibootz

Related questions

...