strings.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "fmt"
  4. "unicode/utf8"
  5. )
  6. func main() {
  7. // пустая строка по-умолчанию
  8. var str string
  9. // со спец символами
  10. var hello string = "Привет\n\t"
  11. // без спец символов
  12. var world string = `Мир\n\t`
  13. fmt.Println("str", str)
  14. fmt.Println("hello", hello)
  15. fmt.Println("world", world)
  16. // UTF-8 из коробки
  17. var helloWorld = "Привет, Мир!"
  18. hi := "你好,世界"
  19. fmt.Println("helloWorld", helloWorld)
  20. fmt.Println("hi", hi)
  21. // одинарные кавычки для байт (uint8)
  22. var rawBinary byte = '\x27'
  23. // rune (uint32) для UTF-8 символов
  24. var someChinese rune = '茶'
  25. fmt.Println(rawBinary, someChinese)
  26. helloWorld = "Привет Мир"
  27. // конкатенация строк
  28. andGoodMorning := helloWorld + " и доброе утро!"
  29. fmt.Println(helloWorld, andGoodMorning)
  30. // строки неизменяемы
  31. // cannot assign to helloWorld[0]
  32. // helloWorld[0] = 72
  33. // получение длины строки
  34. byteLen := len(helloWorld) // 19 байт
  35. symbols := utf8.RuneCountInString(helloWorld) // 10 рун
  36. fmt.Println(byteLen, symbols)
  37. // получение подстроки, в байтах, не символах!
  38. hello = helloWorld[:12] // Привет, 0-11 байты
  39. H := helloWorld[0] // byte, 72, не "П"
  40. fmt.Println(H)
  41. // конвертация в слайс байт и обратно
  42. byteString := []byte(helloWorld)
  43. helloWorld = string(byteString)
  44. fmt.Println(byteString, helloWorld)
  45. }