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 slice of words using Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "strings"
    "time"
)

func replaceRandomWord(text string, replacements []string) string {
    words := strings.Split(text, " ")

    if len(words) == 0 || len(replacements) == 0 {
        return text // nothing to do
    }

    // Seed the random generator
    rand.Seed(time.Now().UnixNano())

    // Pick random index in the sentence
    idx := rand.Intn(len(words))

    // Pick random replacement word
    newWord := replacements[rand.Intn(len(replacements))]

    // Replace it
    words[idx] = newWord

    // Rebuild the string
    return strings.Join(words, " ")
}

func main() {
    text := "The quick brown fox jumps over the lazy dog"
    replacements := []string{"c#", "c++", "java", "rust", "python"}

    result := replaceRandomWord(text, replacements)
    fmt.Println(result)
}



/*
run:

The quick brown fox jumps python the lazy dog

*/

 



answered 5 hours ago by avibootz

Related questions

2 answers 243 views
2 answers 187 views
1 answer 160 views
...