Standard library / strings

strings.ToValidUTF8()

Replaces each contiguous run of invalid UTF-8 bytes with replacement; replacement itself should be valid UTF-8 for valid output. Expected stdout: 'a?b\n'.

Formal Syntax & Structure

go syntaxgo
func ToValidUTF8(s, replacement string) string

Parameters & Attributes

NameTypeDescription
sstringInput text or sequence.
replacementstringReplacement for each run of invalid UTF-8 bytes.

Return Value

string

Replaces each contiguous run of invalid UTF-8 bytes with replacement; replacement itself should be valid UTF-8 for valid output.

Working Example

Example Snippetgo
package main
import (  "fmt"  "strings")
func main() {  fmt.Println(string(strings.ToValidUTF8("a\xff\xfeb", "?")))}
Go Reference