strings.ToValidUTF8() Function in Golang With Examples

strings.ToValidUTF8() Function in Golang is used to returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.

Syntax:

func ToValidUTF8(str, rep string) string

Here, str is string which may contain invalid UTF-8 and rep is the replacement string.

Return Value: It returns the replaced string.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show the usage
// of strings.ToValidUTF8() Function
package main
  
// importing fmt and strings
import (
    "fmt"
    "strings"
)
  
// calling main method
func main() {
  
    // There is no invalid UTF-8 character
    // present, so the same string returned
    fmt.Print(strings.ToValidUTF8("This is GeeksForGeeks", " "))
}

chevron_right


Output:

This is GeeksForGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show the usage
// of strings.ToValidUTF8() Function
package main
  
// importing fmt and strings
import (
    "fmt"
    "strings"
)
  
// calling main method
func main() {
  
    // Invalid UTF-8 '\xc5' replaced by 'For'
    fmt.Print(strings.ToValidUTF8("Geeks\xc5Geeks", "For"))
}

chevron_right


Output:

GeeksForGeeks
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.