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

How to extract strings one by one in go language

青灯夜游
Release: 2021-06-04 16:27:38
Original
3275 people have browsed it

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])
	}
}
Copy after login

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
Copy after login

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)
	}
}
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template