Golang strconv Package

Many times, while writing the codes, we often need to use string and other types of conversions, the strconv package can help us achieve this function.

In Go language, the strconv package implements conversions to and from string representations of basic data types. The strconv package has a variety of constants and mathematical functions related to, from the string conversions. To use these strconv package functions – we need to import the strconv package.

Golang strconv Package Constants, Variables, and Functions

The strconv package has a set of constants, variables, and functions.

Constants

Constant Description
strconv.IntSize It returns the size in bits of an int or uint value

Variables

Variable Description
strconv.ErrRange It indicates that a value is out of range for the target type. The value of the ErrRange variable is "value out of range".
strconv.ErrSyntax It indicates that a value does not have the right syntax for the target type. The value of the ErrSyntax variable is "invalid syntax".

Functions

Function Description
strconv.AppendBool() It appends the bool values ("true" or "false"), according to the value of b, to dst and returns the extended buffer. Where dst is the first parameter of []byte type and b is the second parameter of the bool type.
strconv.AppendFloat() It appends the string form of the given floating-point number f (as generated by FormatFloat() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and f is the second parameter of float64 type.
strconv.AppendInt() It appends the string form of the given integer number i (as as generated by FormatInt() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and i is the second parameter of int64 type.
strconv.AppendQuote() It appends the double-quoted Go string literal representing s (as generated by Quote() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and s is the second parameter of string type.
strconv.AppendQuoteRune() It appends the single-quoted Go character literal representing the r (as generated by QuoteRune() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and r is the second parameter of rune type.
strconv.AppendQuoteRuneToASCII() It appends the single-quoted Go character literal representing the r (as generated by QuoteRuneToASCII() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and r is the second parameter of rune type.
strconv.AppendQuoteRuneToGraphic() It appends the single-quoted Go character literal representing the r (as generated by QuoteRuneToGraphic() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and r is the second parameter of rune type.
strconv.AppendQuoteToASCII() It appends the double-quoted Go string literal representing s (as generated by QuoteToASCII() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and s is the second parameter of string type.
strconv.AppendQuoteToGraphic() It appends the double-quoted Go string literal representing s (as generated by QuoteToGraphic() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and s is the second parameter of string type.
strconv.AppendUint() It appends the string form of the unsigned integer i (as generated by FormatUint() function), to dst and returns the extended buffer. Where dst is the first parameter of []byte type and i is the second parameter of uint64 type.
strconv.Atoi() It converts (interprets) a given string s in the given base (10) and bit size (0) and returns the corresponding integer value. The Atoi() function is equivalent to ParseInt(s, 10, 0), converted to type int.
strconv.CanBackquote() It checks whether the given string can be represented unchanged as a single-line backquoted string without control characters other than the tab.
strconv.FormatBool() It returns "true" or "false" according to the given value of b. Where b is the bool type. Or, we can say that the FormatBool() function is used to convert a bool value to a string.
strconv.FormatComplex() It converts the given complex number c to a string of the form (a+bi) where a is the real part and b is the imaginary part of the complex number, the formatting is done based on the format fmt and precision prec.
strconv.FormatFloat() It converts the given floating-point number f to a string, the formatting is done based on the format fmt and precision prec. The function rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (where, 32 for float32, 64 for float64).
strconv.FormatInt() It returns the string representation of the given integer in the given base, where the base can be between 2 to 36 (2 <= base <= 36). The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
strconv.FormatUint() It returns the string representation of the given unsigned integer in the given base, where the base can be between 2 to 36 (2 <= base <= 36). The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
strconv.IsGraphic() It checks whether the given rune is defined as a Graphic by Unicode. Graphic characters include letters, marks, numbers, punctuation, symbols, and spaces, from categories L, M, N, P, S, and Zs.
strconv.IsPrint() It checks whether the given rune is defined as printable by Go, with the same definition as unicode.IsPrint() function: As per the Go, IsPrint() returns true for the letters, numbers, punctuation, symbols, and ASCII space.
strconv.Itoa() It returns the string representation of the given integer (int). The Itoa() function is equivalent to FormatInt(int64(i), 10).
strconv.ParseBool() It returns the boolean value represented by the given string. The function accepts only 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.
strconv.ParseComplex() It converts the given string s to a complex number with the precision specified by bitSize (Value of bitSize must be 64 or 128, 64 is used for complex64, and 128 is used for complex128). When bitSize=64, the converted result still has type complex128, but it will be convertible to complex64 without changing its value.
strconv.ParseFloat() It converts the given string s to a floating-point number with the precision specified by bitSize (Value of bitSize must be 32 or 64, 32 is used for float32, or 64 is used for float64). When bitSize=32, the converted result still has type float64, but it will be convertible to float32 without changing its value.
strconv.ParseInt() It converts the given string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding integer value i. The given string may begin with a leading sign: "+" or "-" to convert as a positive or negative integer.
strconv.ParseUint() It converts the given string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding unsigned integer value i. The ParseUint() function is similar to ParseInt() but for unsigned integers only, the sign (+ or -) is not allowed.
strconv.Quote() It returns a double-quoted Go string literal representing the given string s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint() function.
strconv.QuoteRune() It returns a single-quoted Go character literal representing the rune r. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint() function.
strconv.QuoteRuneToASCII() It returns a single-quoted Go character literal representing the rune r. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint() function.
strconv.QuoteRuneToGraphic() It returns a single-quoted Go character literal representing the rune r. If the rune is not a Unicode graphic character, as defined by IsGraphic() function, the returned string will use a Go escape sequence (\t, \n, \xFF, \u0100).
strconv.QuoteToASCII() It returns a double-quoted Go string literal representing the given string s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint() function.
strconv.QuoteToGraphic() It returns a double-quoted Go string literal representing the given string s. The returned string leaves Unicode graphic characters, as defined by IsGraphic() function, unchanged and uses Go escape sequences (\t, \n, \xFF, \u0100) for non-graphic characters.
strconv.QuotedPrefix() It returns the quoted-string (as understood by Unquote) at the prefix of the given string. If the string does not start with a valid quoted string, QuotedPrefix() returns an error.
strconv.Unquote() It interprets the given string s as a single-quoted, double-quoted, or backquoted, and returns the string value that s quotes. (If there is a single-quoted string, the function returns the corresponding one-character string.)
strconv.UnquoteChar() It decodes the first character or byte in the escaped string or character literal represented by the string s. It returns four values (value of quote character, multibyte status, tail string, and an error).

Example of strconv.AppendBool()

// Golang program to demonstrate the
// example of strconv.AppendBool() Function

package main

import (
	"fmt"
	"strconv"
)

func main() {
	x := []byte("Bool:")
	fmt.Println("Before appending...")
	fmt.Println("x:", string(x))
	fmt.Println("Length(x): ", len(x))

	// Appending 'true' and then 'false'
	x = strconv.AppendBool(x, true)
	x = strconv.AppendBool(x, false)

	fmt.Println("After appending...")
	fmt.Println("x:", string(x))
	fmt.Println("Length(x): ", len(x))
}

Output:

Before appending...
x: Bool:
Length(x):  5
After appending...
x: Bool:truefalse
Length(x):  14

Example of strconv.UnquoteChar()

// Golang program to demonstrate the
// example of strconv.UnquoteChar() Function

package main

import (
	"fmt"
	"strconv"
)

func main() {
	value, mb, tail, err := strconv.UnquoteChar(`\"Hello, world!\"`, '"')
	if err != nil {
		fmt.Println("Error:", err)
	}

	fmt.Println("value:", string(value))
	fmt.Println("multibyte:", mb)
	fmt.Println("tail:", tail)
	fmt.Println()

	value, mb, tail, err = strconv.UnquoteChar("\"Hello, world!\"", '"')
	if err != nil {
		fmt.Println("Error:", err)
	}

	fmt.Println("value:", string(value))
	fmt.Println("multibyte:", mb)
	fmt.Println("tail:", tail)
	fmt.Println()
}

Output:

value: "
multibyte: false
tail: Hello, world!\"

Error: invalid syntax
value: 
multibyte: false
tail: 

Example of strconv.ParseInt()

// Golang program to demonstrate the
// example of strconv.ParseInt() Function

package main

import (
	"fmt"
	"strconv"
)

func main() {
	v := "12345678"

	s, err := strconv.ParseInt(v, 10, 32)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()

	v = "-123456789098765"
	s, err = strconv.ParseInt(v, 10, 64)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()

	v = "1234567890987654321"
	s, err = strconv.ParseInt(v, 10, 64)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()

	v = "1111111111111111111111000000000111111"
	s, err = strconv.ParseInt(v, 2, 64)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()

	v = "ffffffffff"
	s, err = strconv.ParseInt(v, 16, 32)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
}

Output:

Parsing done...
int64, 12345678

Parsing done...
int64, -123456789098765

Parsing done...
int64, 1234567890987654321

Parsing done...
int64, 137438920767

Parsing failed...
Error:strconv.ParseInt: parsing "ffffffffff": value out of range



Comments and Discussions!

Load comments ↻






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