본문 바로가기
Go

[Go] Rune and String

by llHoYall 2021. 10. 16.

A string is a set of characters and a string is an immutable.

Syntax

A rune can be represented by '(single quote) and it means single character.

Go supports UTF-8 as a standard character code.

package main

import "fmt"

func main() {
  fmt.Printf("%c\n", 'G')
  fmt.Printf("%c\n", '고')
  fmt.Printf("%c\n", '去')
}

A string can be represented by "(double-quote) or `(backquote or backtick or grave).

A special character works in the double-quote and doesn't work in the backquote.

package main

import "fmt"

func main() {
  fmt.Print("Hello\tWorld\n")
  // Hello   World

  fmt.Print(`Hello\tWorld\n`)
  // Hello\tWorld\n
}

A double-quote needs a newline character when you want to put a multiline string, but a backquote doesn't need it.

fmt.Println("1st string\n2nd string\n3rd string")
// 1st string
// 2nd string
// 3rd string

fmt.Println(`1st string
2nd string
3rd string`)
// 1st string
// 2nd string
// 3rd string

Length of a String

The len() function returns the size of the memory the string occupies.

fmt.Printf("%d\n", len("ABC")) // 3
fmt.Printf("%d\n", len("가나다")) // 9

A single Korean character occupies 3 bytes in Go (UTF-8).

Traverse a String

str := "Hello 월드"

for i := 0; i < len(str); i++ {
  fmt.Printf("%c", str[i])
}
// Hello ìë

If you access a string by index, it is treated by uint8.

So it cannot handle Unicode character

str := "Hello 월드"
runeArr := []rune(str)

for i := 0; i < len(runeArr); i++ {
  fmt.Printf("%c", runeArr[i])
}
// Hello 월드

It can be handled by a convert to a rune slice.

str := "Hello 월드"

for _, v := range str {
  fmt.Printf("%c", v)
}
// Hello 월드

Or it can be handled by for range.

This method doesn't need additional memory space.

Join Strings

A string can be joined by the + symbol in Go.

str1 := "Hello"
str2 := "World"

fmt.Println(str1 + " " + str2)
// Hello World

Whenever a string combination occurs, memory is wasted because the combined result is stored in the new memory.

str1 := "Hello"
str2 := "World"

var builder strings.Builder
builder.WriteString(str1 + " " + str2)

fmt.Println(builder.String())
// Hello World

You can reduce it using Builder in the strings package.

Because, strings.Builder uses its inner slice memory space.

Structure of String in Go

String in Go has the following structure. You can find it in the reflect package.

type StringHeader struct {
  Data uintptr
  Len  int
}

String points to a memory space that is included a string.

So, copying a string just copy the pointer.

'Go' 카테고리의 다른 글

[Go] Slice  (0) 2021.10.16
[Go] Package  (0) 2021.10.16
[Go] Pointer  (0) 2021.10.11
[Go] Structure  (0) 2021.10.11
[Go] Array  (0) 2021.10.10

댓글