Home >Backend Development >Golang >How to find a specified substring in a string in Go language

How to find a specified substring in a string in Go language

青灯夜游
青灯夜游Original
2021-06-18 11:56:534666browse

In the Go language, you can use slicing with the "strings.Index()" function to find the specified substring. The syntax format is "string[strings.Index(string, "Character") strings.Index( String[start position:], "character"):]". The Index() function of the strings package can search for another substring in a string and obtain the start and end positions of the substring.

How to find a specified substring in a string in Go language

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

Getting a certain section of characters in a string is a common operation in development. We generally call a certain section of characters in a string a substring.

In the following example, the strings.Index() function is used to search for another substring in the string. The code is as follows:

tracer := "死神来了, 死神bye bye"
comma := strings.Index(tracer, ", ")
pos := strings.Index(tracer[comma:], "死神")
fmt.Println(comma, pos, tracer[comma+pos:])

The program output is as follows:

12 3 死神bye bye

The code description is as follows :

1) Line 2 attempts to search for Chinese commas in the tracer string. The returned position is stored in the comma variable. The type is int, which represents the ASCII code position starting from the tracer string.

The strings.Index() function does not provide a function to start searching from a certain offset like other languages. However, we can perform slicing operations on strings to implement this logic.

2) In line 4, tracer[comma:] constructs a substring from the comma position of tracer to the end of the tracer string, and returns it to string.Index() for re-indexing. The resulting pos is relative to tracer[comma:].

comma The comma position is 12, while pos is a relative position with a value of 3. In order to obtain the position of the second "god of death", which is the string after the comma, we must add comma to the relative offset of pos, calculate the offset of 15, and then calculate it through slice tracer[comma pos:] Get the final substring and get the final result: "Death bye bye".

Recommended learning: Golang tutorial

The above is the detailed content of How to find a specified substring in a string 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