strconv
공식 문서: strconv package - strconv - Go Packages
strconv 패키지는 기본 데이터 타입의 문자열 표현과의 간 변환을 구현합니다.
가져오기
go
import (
"strconv"
)아래에서는 예시를 통해 사용 방법을 설명하겠습니다.
문자열을 정수로 변환
go
func Atoi(s string) (int, error)s- 변환할 문자열
go
func TestAoti(t *testing.T) {
ints, err := strconv.Atoi("456789")
fmt.Println(ints, err)
}=== RUN TestAoti
456789 <nil>
--- PASS: TestAoti (0.00s)
PASS정수를 문자열로 변환
go
func Itoa(i int) stringi- 변환할 정수 숫자
go
func TestIota(t *testing.T) {
str := strconv.Itoa(114)
fmt.Println(str)
}=== RUN TestIota
114
--- PASS: TestIota (0.00s)
PASS문자열을 불리언으로 변환
go
func ParseBool(str string) (bool, error)s- 변환할 문자열
변환 가능한 문자열은 다음과 같습니다.
"1", "t", "T", "true", "TRUE", "True" // true
"0", "f", "F", "false", "FALSE", "False" // falsego
func TestAtob(t *testing.T) {
parseBool, err := strconv.ParseBool("1")
fmt.Println(parseBool, err)
b, err := strconv.ParseBool("true")
fmt.Println(b, err)
b2, err := strconv.ParseBool("FALSE")
fmt.Println(b2, err)
}=== RUN TestAotb
true <nil>
true <nil>
false <nil>
--- PASS: TestAotb (0.00s)
PASS불리언을 문자열로 변환
go
func FormatBool(b bool) stringb- 불리언 값
go
func TestBota(t *testing.T) {
fmt.Println(strconv.FormatBool(true))
fmt.Println(strconv.FormatBool(false))
}=== RUN TestBota
true
false
--- PASS: TestBota (0.00s)
PASSGo 문자열로 변환
둘 다 문자열을 따옴표가 있는 Go 문자열로 변환합니다. 차이는 후자가 비 ASCII 문자를 \u 로 이스케이프한다는 점입니다.
go
func TestQuote(t *testing.T) {
fmt.Println(strconv.Quote("hello 世界"))
fmt.Println(strconv.QuoteToASCII("hello 世界"))
}=== RUN TestQuote
"hello 世界"
"hello \u4e16\u754c"
--- PASS: TestQuote (0.00s)
PASS문자열을 부동소수점으로 변환
go
func ParseFloat(s string, bitSize int) (float64, error)s- 변환할 문자열bitSize- 비트 수
go
func TestParseFloat(t *testing.T) {
float, err := strconv.ParseFloat("1.145114", 64)
fmt.Println(float, err)
float, err = strconv.ParseFloat("2.3333333333333333333", 64)
fmt.Println(float, err)
}=== RUN TestFloat
1.145114 <nil>
2.3333333333333335 <nil>
--- PASS: TestFloat (0.00s)
PASS부동소수점을 문자열로 변환
문자열이 부동소수점으로 변환될 때 공식에서는 여러 가지 형식 방법을 제공하여 다양한 스타일을 출력할 수 있습니다.
// 'b' (-ddddp±ddd, 이진 지수),
// 'e' (-d.dddde±dd, 소문자 e 십진 지수),
// 'E' (-d.ddddE±dd, 대문자 E 십진 지수),
// 'f' (-ddd.dddd, 지수 없음), // 특별한 요구사항이 없으면 일반적으로 이것을 사용
// 'g' (큰 지수는 'e' 형식, 작은 지수는 'f' 형식 사용),
// 'G' (큰 지수는 'E' 형식, 작은 지수는 'f' 형식 사용),
// 'x' (-0xd.ddddp±ddd, 16 진수 분수와 이진 지수),
// 'X' (-0Xd.ddddP±ddd, 16 진수 분수와 이진 지수).변환 함수
go
func FormatFloat(f float64, fmt byte, prec, bitSize int) string- f - 변환할 부동소수점
- fmt - 형식화 타입
- prec - 정밀도,
g/G의 경우 최대 유효 자릿수를 나타내며, 그 외의 경우 소수점 이하 자릿수를 나타냄 - bitSize - 비트 수
일반적인 경우에는 f 를 사용하여 소수 형식으로 변환하는 것이 가장 일반적입니다.
go
func TestFormatFloat(t *testing.T) {
f := 1315643.14159261234567891011
fmt.Println(strconv.FormatFloat(f, 'f', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'b', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'e', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'x', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'g', 6, 64))
fmt.Println(strconv.FormatFloat(1.111, 'g', 6, 64))
}=== RUN TestFormatFloat
1315643.141593
5650644266346967p-32
1.315643e+06
0x1.4133b2p+20
1.31564e+06
1.111
--- PASS: TestFormatFloat (0.00s)
PASS문자열을 복소수로 변환
go
func ParseComplex(s string, bitSize int) (complex128, error)s- 변환할 문자열bitSize- 비트 수
go
func TestParseComplex(t *testing.T) {
fmt.Println(strconv.ParseComplex("1+2i", 128))
fmt.Println(strconv.ParseComplex("1+2j", 128))
}=== RUN TestParseComplex
(1+2i) <nil>
(0+0i) strconv.ParseComplex: parsing "1+2j": invalid syntax
--- PASS: TestParseComplex (0.00s)
PASS복소수를 문자열로 변환
go
func FormatComplex(c complex128, fmt byte, prec, bitSize int) stringc - 복소수
fmt - 형식화 타입, 부동소수점 형식화 타입 참조
prec - 부동소수점 정밀도 참조
bitsize - 비트 수
go
func TestFormatComplex(t *testing.T) {
fmt.Println(strconv.FormatComplex(complex(1.1, 12), 'f', 2, 128))
fmt.Println(strconv.FormatComplex(complex(5.6, 2.8), 'b', 2, 128))
fmt.Println(strconv.FormatComplex(complex(18.88999, 89.7), 'g', 2, 128))
}=== RUN TestFormatComplex
(1.10+12.00i)
(6305039478318694p-50+6305039478318694p-51i)
(19+90i)
--- PASS: TestFormatComplex (0.00s)
PASS문자열에 데이터 추가
Java 와 같은 다른 언어에서는 "1"+1 의 결과가 "11" 이며, Java 는 자동으로 타입 변환을 수행합니다. 그러나 Go 언어에서는 이러한 연산이 허용되지 않습니다. 데이터 타입이 다르기 때문입니다. 따라서 strconv 의 Append 함수를 사용해야 합니다. 구체적인 매개변수는 위의 데이터 변환 함수와 동일합니다.
go
func TestAppend(t *testing.T) {
bytes := []byte("여기에 일부 데이터가 있습니다:")
bytes = strconv.AppendInt(bytes, 10, 10)
bytes = strconv.AppendFloat(bytes, 1.2222, 'f', 2, 64)
bytes = strconv.AppendBool(bytes, false)
fmt.Println(string(bytes))
}=== RUN TestAppend
여기에 일부 데이터가 있습니다:101.22false
--- PASS: TestAppend (0.00s)
PASS