×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.ToValidUTF8() Function with Examples

Golang | strings.ToValidUTF8() Function: Here, we are going to learn about the ToValidUTF8() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 23, 2021

strings.ToValidUTF8()

The ToValidUTF8() function is an inbuilt function of strings package which is used to get a copy of the string with each run of invalid UTF-8 byte sequences replaced by the replacement string. It accepts two parameters – a string and a replacement string and returns the string with invalid UTF-8 byte sequences replaced by the replacement string.

Syntax

func ToValidUTF8(str, replacement string) string

Parameters

  • str : The string to be checked and replaced invalid UTF-8 byte sequence (if any)
  • replacement : The string to be replaced with an invalid UTF-8 byte sequence, it may be an empty string.

Return Value

The return type of ToValidUTF8() function is a string, it returns a copy of the string with each run of invalid UTF-8 byte sequences replaced by the replacement string.

Example 1

// Golang program to demonstrate the
// example of strings.ToValidUTF8() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ToValidUTF8("Hello, world!", ""))
	fmt.Println(strings.ToValidUTF8("Hello, world!", "OKAY"))

	// Here, \xC9 is an invalid UTF-8 byte
	// and, it will be replaced with OKAY
	fmt.Println(strings.ToValidUTF8("Hello,\xC9world!", "OKAY"))

	// Here, \x41 is a valid UTF-8 for character 'A'
	// but, \xC9 is invalid which will be ignored
	fmt.Println(strings.ToValidUTF8("Hello,\xC9\x41 world!", ""))
}

Output:

Hello, world!
Hello, world!
Hello,OKAYworld!
Hello,A world!

Example 2

// Golang program to demonstrate the
// example of strings.ToValidUTF8() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	// replacing with empty string i.e.,
	// ignoring the invalid UTF-8 byte sequences
	fmt.Println(strings.ToValidUTF8("A\xfcB\xa1C\xa1D\xa1E\xa1F\xa1", ""))

	// replacing with space
	fmt.Println(strings.ToValidUTF8("A\xfcB\xa1C\xa1D\xa1E\xa1F\xa1", " "))

	// replacing with ", "
	fmt.Println(strings.ToValidUTF8("A\xfcB\xa1C\xa1D\xa1E\xa1F\xa1", ", "))

	// there is no invalid UTF-8 byte sequence
	fmt.Println(strings.ToValidUTF8("Hello, world!", ""))
}

Output:

ABCDEF
A B C D E F 
A, B, C, D, E, F, 
Hello, world!

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.