Home >Backend Development >Golang >How to extract strings one by one in go language

How to extract strings one by one in go language

青灯夜游
青灯夜游Original
2021-06-04 16:27:383301browse

Method: First use the for statement to traverse the string, the syntax "for i := 0; i < len (string variable); i {}" or "for _, s := range string variable {}"; then use the "fmt.Printf()" function in the loop body "{}" to output one by one.

How to extract strings one by one in go language

The operating environment of this tutorial: Windows 10 system, GO 1.11.2, Dell G3 computer.

Go language traverses strings - obtains each string element

Traverses each ASCII character

Traverse ASCII characters using for's numerical loop to traverse, directly get the subscript of each string to obtain the ASCII characters, as shown in the following example.

package main

import "fmt"

func main() {
    theme := "hello php中文网"
	for i := 0; i < len(theme); i++ {
		fmt.Printf("ascii: %c  %d\n", theme[i], theme[i])
	}
}

The program output is as follows:

ascii: h  104
ascii: e  101
ascii: l  108
ascii: l  108
ascii: o  111
ascii:    32
ascii: p  112
ascii: h  104
ascii: p  112
ascii: ä  228
ascii: ¸  184
ascii: ­  173
ascii: æ  230
ascii: –  150
ascii: ‡  135
ascii: ç  231
ascii: ½  189
ascii: ‘  145

The Chinese characters obtained in this mode are "horrible". Since Unicode is not used, Chinese characters are displayed as garbled characters.

Traverse the string by Unicode characters

Same content:

package main

import "fmt"

func main() {
    theme := "hello php中文网"
	for _, s := range theme {
		fmt.Printf("Unicode: %c  %d\n", s, s)
	}
}

The program output is as follows:

Unicode: h  104
Unicode: e  101
Unicode: l  108
Unicode: l  108
Unicode: o  111
Unicode:    32
Unicode: p  112
Unicode: h  104
Unicode: p  112
Unicode: 中  20013
Unicode: 文  25991
Unicode: 网  32593

You can see, This time Chinese characters can be output normally.

Summary

  • ASCII string traversal uses subscripts directly.

  • Unicode string traversal uses for range.

Recommended learning: Golang tutorial

The above is the detailed content of How to extract strings one by one in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn