strings.ContainsFunc And IndexFunc

Locate characters by predicate instead of literal: IndexFunc reports the first match, ContainsFunc answers membership, LastIndexFunc scans from the end.

GoData Integrity

Code

gosnippet
32 lines
package main

import (
	"fmt"
	"strings"
	"unicode"
	"unicode/utf8"
)

func main() {
	line := "req id=42, tag=Ω, ok"

	// IndexFunc:按谓词找第一个命中的字节索引,找不到返回 -1
	first := strings.IndexFunc(line, unicode.IsUpper)
	r, _ := utf8.DecodeRuneInString(line[first:])
	fmt.Printf("first uppercase at %d: %c\n", first, r)

	// ContainsFunc:只要布尔答案时的写法,不必拿索引
	fmt.Println("has any digit:", strings.ContainsFunc(line, unicode.IsDigit))

	// LastIndexFunc:从尾部反向扫描,定位最后一个命中
	last := strings.LastIndexFunc(line, unicode.IsDigit)
	lr, _ := utf8.DecodeRuneInString(line[last:])
	fmt.Printf("last digit at %d: %c\n", last, lr)

	// 谓词是普通函数:自定义规则(空格或逗号)同样适用
	splitter := func(r rune) bool { return r == ' ' || r == ',' }
	fmt.Println("first separator:", strings.IndexFunc(line, splitter))

	// 命中索引可用来切片:从最后一个数字的位置取尾部
	fmt.Println("tail:", line[last:])
}

Predicate-driven scanning

One main exercises every predicate helper the snippet defines.

Caveats

  • The imports reduce to strings and unicode — both ship with Go itself, so there is nothing to install.

Applying it

The entry-point signature is func main()

The run emits 5 labeled sections — first uppercase at, has any digit:, last digit at, first separator:, tail: — one per step.

Where the matches land

splitter := func(r rune) bool { return r == ' ' || r == ',' }

Interactive Tools for This Topic

FAQ

What does strings.ContainsFunc And IndexFunc print when run?
Execute the whole file; each printed line is prefixed with a label like `first uppercase at`, `has any digit:`, `last digit at`.