【函数探析】strings.IndexFunc(s, f) in go

先决条件

  1. 字符编码笔记:ASCII,Unicode 和 UTF-8_阮一峰
  2. 理解 go 中的 rune

在 go 中,我们要在一个字符串中查找符合要求的字符,就可以使用IndexFunc(s, f)方法。

func IndexFunc(s string, f func(rune) bool) int

第一个参数字符串 s 表示要父串。
第二个参数是一个函数(函数参数为 rune,返回值为 bool),这个函数用于对字符串 s,进行一个字符一个字符的判断,即会把 s 中的每一个字符作为参数放到后面的函数中进行判断。
返回值,函数的返回值为 int,如果函数为 1,则表示 s 中存在符合要求的字符,如果为 -1,则表示没有。

以下是这个函数实现的源码

// IndexFunc returns the index into s of the first Unicode
// code point satisfying f(c), or -1 if none do.
func IndexFunc(s string, f func(rune) bool) int {
    
    
	return indexFunc(s, f, true)
}

可以看到 IndexFunc这个函数中主要实现的又是 indexFunc这个函数,下面我们来看看这个函数的实现

// indexFunc 和 IndexFunc 类似,除非
// 没有在父串 s 中找到符合要求的字符
// 此时将返回 -1
func indexFunc(s string, f func(rune) bool, truth bool) int {
    
    
	for i, r := range s {
    
    
		if f(r) == truth {
    
    
			return i
		}
	}
	return -1
}

indexFunc中通过 for range对父串 s 进行遍历,每一个父串 s 中的元素都会被放入自己书写的 f func(rune) bool中进行判断(这个函数我们会在下面的小栗子中看到怎么书写),f(r)也就是 f func(rune) bool会返回判断的结果,如果存在则返回第一次符合要求的位置(注,下标从 0 开始)。

下面举一个小栗子来感受一下

package main

import (
	"fmt"
	"strings"
)

func main() {
    
    
	ans := strings.IndexFunc("Abc", checkRune)
	fmt.Println(ans) // 1
	ans = strings.IndexFunc("Ac", checkRune)
	fmt.Println(ans) // -1
}

// checkRune 判断是否存在字符 b,如果存在则返回 true,反之则返回 false
func checkRune(r rune) bool {
    
    
	if r == 'b' {
    
    
		return true
	}
	return false
}

猜你喜欢

转载自blog.csdn.net/qq_34902437/article/details/120957657