mrfr
mrfr

Reputation: 1794

Replace a character at a specific location in a string

I know about the method string.Replace(). And it works if you know exactly what to replace and its occurrences. But what can I do if I want to replace a char at only a known position? I'm thinking of something like this:

randLetter := getRandomChar()

myText := "This is my text"

randPos :=  rand.Intn(len(myText) - 1)

newText := [:randPos] + randLetter + [randPos + 1:]

But this does not replace the char at randPos, just inserts the randLetter at that position. Right?

Upvotes: 1

Views: 1667

Answers (2)

Pwnstar
Pwnstar

Reputation: 2245

I've written some code to replace the character found at indexofcharacter with the replacement. I may not be the best method, but it works fine.

https://play.golang.org/p/9CTgHRm6icK

func replaceAtPosition(originaltext string, indexofcharacter int, replacement string) string {
    runes := []rune(originaltext )
    partOne := string(runes[0:indexofcharacter-1])
    partTwo := string(runes[indexofcharacter:len(runes)])
    return partOne + replacement + partTwo
}

Upvotes: 1

Jürgen Hötzel
Jürgen Hötzel

Reputation: 19727

A string is a read-only slice of bytes. You can't replace anything.

A single Rune can consist of multiple bytes. So you should convert the string to a (intermediate) mutable slice of Runes anyway:

myText := []rune("This is my text")
randPos := rand.Intn(len(myText) - 1)
myText[randPos] = randLetter
fmt.Println(string(myText))

Upvotes: 0

Related Questions