×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.IndexFunc() Function with Examples

Golang | strings.IndexFunc() Function: Here, we are going to learn about the IndexFunc() function of strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 16, 2021

strings.IndexFunc()

The IndexFunc() function is an inbuilt function of strings package which is used to get the index of the first Unicode code point satisfying the function with respect to the character of the string. It accepts two parameters – string and a function and returns the index, or -1 if any character of the string does not satisfy the function.

Syntax

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

Parameters

  • str : String in which we have to check the character through the function
  • f : Function that contains the condition

Return Value

The return type of IndexFunc() function is an int, it returns the index, or -1 if any character of the string does not satisfy the function.

Example 1

// Golang program to demonstrate the
// example of strings.IndexFunc() Function

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	// function to check character
	// is in lowercase or not
	f := func(c rune) bool {
		return unicode.IsLower(c)
	}

	fmt.Println(strings.IndexFunc("HELLO, World!", f))
	fmt.Println(strings.IndexFunc("HELLO, WORLD!", f))
}

Output:

8
-1

Example 2

// Golang program to demonstrate the
// example of strings.IndexFunc() Function

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	var str string
	// function to check character
	// is in lowercase or not
	fLower := func(c rune) bool {
		return unicode.IsLower(c)
	}

	// function to check character
	// is in uppercase or not
	fUpper := func(c rune) bool {
		return unicode.IsUpper(c)
	}

	// function to check character
	// is a digist or not
	fDigit := func(c rune) bool {
		return unicode.IsDigit(c)
	}

	str = "Hello, World!"
	fmt.Println("Lowercase Character's Index:", strings.IndexFunc(str, fLower))
	fmt.Println("Uppercase Character's Index:", strings.IndexFunc(str, fUpper))
	fmt.Println("Digit's Index:", strings.IndexFunc(str, fDigit))

	str = "Okay@123!"
	fmt.Println("Lowercase Character's Index:", strings.IndexFunc(str, fLower))
	fmt.Println("Uppercase Character's Index:", strings.IndexFunc(str, fUpper))
	fmt.Println("Digit's Index:", strings.IndexFunc(str, fDigit))
}

Output:

Lowercase Character's Index: 1
Uppercase Character's Index: 0
Digit's Index: -1
Lowercase Character's Index: 1
Uppercase Character's Index: 0
Digit's Index: 5

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.