Golang strings.ContainsFunc Function

The strings.ContainsFunc function in Golang is part of the strings package and is used to determine whether a string contains at least one Unicode code point that satisfies a given function. This function is useful when you need to apply complex logic to check for the presence of specific characters based on custom criteria, such as checking for non-alphanumeric characters, whitespace, or specific Unicode ranges.

Table of Contents

  1. Introduction
  2. ContainsFunc Function Syntax
  3. Examples
    • Basic Usage
    • Checking for Non-Alphanumeric Characters
  4. Real-World Use Case
  5. Conclusion

Introduction

The strings.ContainsFunc function allows you to search for characters in a string that meet specific conditions defined by a user-supplied function. This function can be particularly helpful for implementing custom validation rules and searching for characters that meet complex criteria.

ContainsFunc Function Syntax

The syntax for the strings.ContainsFunc function is as follows:

func ContainsFunc(s string, f func(rune) bool) bool

Parameters:

  • s: The main string to be searched.
  • f: A function that takes a rune (a Unicode code point) as an argument and returns a boolean. The function defines the condition to be satisfied by the characters in the string.

Returns:

  • A boolean value (true or false) indicating whether any character in the string satisfies the condition defined by the function f.

Examples

Basic Usage

This example demonstrates how to use the strings.ContainsFunc function to check if a string contains any uppercase letters.

Example

package main

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

func main() {
	// Define the main string
	str := "Hello, Golang!"

	// Use strings.ContainsFunc to check for uppercase letters
	containsUpper := strings.ContainsFunc(str, unicode.IsUpper)

	// Print the result
	if containsUpper {
		fmt.Println("The string contains at least one uppercase letter.")
	} else {
		fmt.Println("The string does not contain any uppercase letters.")
	}
}

Output:

The string contains at least one uppercase letter.

Checking for Non-Alphanumeric Characters

You can use strings.ContainsFunc to verify if a string contains any non-alphanumeric characters.

Example

package main

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

func main() {
	// Define the main string
	str := "Hello@Golang2024"

	// Use strings.ContainsFunc to check for non-alphanumeric characters
	containsNonAlphanumeric := strings.ContainsFunc(str, func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
	})

	// Print the result
	if containsNonAlphanumeric {
		fmt.Println("The string contains non-alphanumeric characters.")
	} else {
		fmt.Println("The string does not contain any non-alphanumeric characters.")
	}
}

Output:

The string contains non-alphanumeric characters.

Real-World Use Case

Custom Input Validation

In real-world applications, strings.ContainsFunc can be used to implement custom input validation rules, such as checking for prohibited characters in usernames.

Example

package main

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

func main() {
	// Define a list of usernames
	usernames := []string{"john_doe", "alice123", "bob@work", "charlie!"}

	// Check each username for prohibited characters
	fmt.Println("Validating usernames:")
	for _, username := range usernames {
		// Check for any character that is not a letter, number, or underscore
		containsProhibited := strings.ContainsFunc(username, func(r rune) bool {
			return !(unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_')
		})

		if containsProhibited {
			fmt.Printf("Invalid username: %s (contains prohibited characters)\n", username)
		} else {
			fmt.Printf("Valid username: %s\n", username)
		}
	}
}

Output:

Validating usernames:
Valid username: john_doe
Valid username: alice123
Invalid username: bob@work (contains prohibited characters)
Invalid username: charlie! (contains prohibited characters)

Conclusion

The strings.ContainsFunc function is a flexible tool for checking if a string contains characters that meet specific criteria defined by a custom function. It is particularly useful for tasks that involve complex character validation or filtering based on custom logic. By using strings.ContainsFunc, you can efficiently implement tailored checks for character presence in your Go programs, making it a valuable function for handling string data and input validation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top