Index And LastIndex Locate Substrings

Locate substrings with strings.Index and strings.LastIndex, treat the -1 result as not-found, and restart the search after a match to find later occurrences.

GoCli Tooling

Code

gosnippet
21 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	line := "key=val key2=val2"

	// Index 找第一次出现,LastIndex 找最后一次出现
	fmt.Println("first  '=' at", strings.Index(line, "="))
	fmt.Println("last   '=' at", strings.LastIndex(line, "="))

	// 找不到时返回 -1,这是与 bool 版 Contains 的关键区别
	fmt.Println("absent token:", strings.Index(line, "missing"))

	// 想跳过第一个匹配:从匹配位置之后继续搜索子串
	second := strings.Index(line[strings.Index(line, "=")+1:], "=")
	fmt.Println("second '=' at", second)
}

How the logic moves

The entry point is the function main — everything else is wiring.

Watch out for

  • The dependency list is empty; the runtime itself covers everything.

Applying it

The main callable is declared as func main()

Look for the first '=' at, last '=' at, absent token: prefixes in the printed output; each one names the step that printed it.

Notable lines

second := strings.Index(line[strings.Index(line, "=")+1:], "=")

Interactive Tools for This Topic

FAQ

What does Index And LastIndex Locate Substrings print when run?
The script runs standalone; its 4 labeled outputs include `first '=' at`, `last '=' at`, `absent token:`.