range_string.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import "fmt"
  3. func main() {
  4. str := "Go is a beautiful language!"
  5. fmt.Printf("The length of str is: %d\n", len(str))
  6. for pos, char := range str {
  7. fmt.Printf("Character on position %d is: %c \n", pos, char)
  8. }
  9. fmt.Println()
  10. str2 := "Chinese: 日本語"
  11. fmt.Printf("The length of str2 is: %d\n", len(str2))
  12. for pos, char := range str2 {
  13. fmt.Printf("character %c starts at byte position %d\n", char, pos)
  14. }
  15. fmt.Println()
  16. fmt.Println("index int(rune) rune char bytes")
  17. for index, rune := range str2 {
  18. fmt.Printf("%-2d %d %U '%c' % X\n", index, rune, rune, rune, []byte(string(rune)))
  19. }
  20. }
  21. /* Output:
  22. The length of str is: 27
  23. Character on position 0 is: G
  24. Character on position 1 is: o
  25. Character on position 2 is:
  26. Character on position 3 is: i
  27. Character on position 4 is: s
  28. Character on position 5 is:
  29. Character on position 6 is: a
  30. Character on position 7 is:
  31. Character on position 8 is: b
  32. Character on position 9 is: e
  33. Character on position 10 is: a
  34. Character on position 11 is: u
  35. Character on position 12 is: t
  36. Character on position 13 is: i
  37. Character on position 14 is: f
  38. Character on position 15 is: u
  39. Character on position 16 is: l
  40. Character on position 17 is:
  41. Character on position 18 is: l
  42. Character on position 19 is: a
  43. Character on position 20 is: n
  44. Character on position 21 is: g
  45. Character on position 22 is: u
  46. Character on position 23 is: a
  47. Character on position 24 is: g
  48. Character on position 25 is: e
  49. Character on position 26 is: !
  50. The length of str2 is: 18
  51. character C starts at byte position 0
  52. character h starts at byte position 1
  53. character i starts at byte position 2
  54. character n starts at byte position 3
  55. character e starts at byte position 4
  56. character s starts at byte position 5
  57. character e starts at byte position 6
  58. character : starts at byte position 7
  59. character starts at byte position 8
  60. character 日 starts at byte position 9
  61. character 本 starts at byte position 12
  62. character 語 starts at byte position 15
  63. index int(rune) rune char bytes
  64. 0 67 U+0043 'C' 43
  65. 1 104 U+0068 'h' 68
  66. 2 105 U+0069 'i' 69
  67. 3 110 U+006E 'n' 6E
  68. 4 101 U+0065 'e' 65
  69. 5 115 U+0073 's' 73
  70. 6 101 U+0065 'e' 65
  71. 7 58 U+003A ':' 3A
  72. 8 32 U+0020 ' ' 20
  73. 9 26085 U+65E5 '日' E6 97 A5
  74. 12 26412 U+672C '本' E6 9C AC
  75. 15 35486 U+8A9E '語' E8 AA 9E
  76. */