Golang strings.Contains Function

The strings.Contains function in Golang is part of the strings package and is used to check if a substring is present within a given string. It returns a boolean value indicating whether the substring exists in the string. This function is useful for searching and verifying the presence of specific text within a string.

Table of Contents

  1. Introduction
  2. Contains Function Syntax
  3. Examples
    • Basic Usage
    • Checking for Substrings in User Input
  4. Real-World Use Case
  5. Conclusion

Introduction

The strings.Contains function provides a simple way to determine if a substring is contained within a string. It is commonly used for string searching, validation, and filtering tasks in Go programs. This function is case-sensitive, meaning it will differentiate between uppercase and lowercase letters when checking for the substring.

Contains Function Syntax

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

func Contains(s, substr string) bool

Parameters:

  • s: The main string to be searched.
  • substr: The substring to search for within the main string.

Returns:

  • A boolean value (true or false) indicating whether the substring is present in the main string.

Examples

Basic Usage

This example demonstrates how to use the strings.Contains function to check for the presence of a substring in a string.

Example

package main

import (
	"fmt"
	"strings"
)

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

	// Check if the substring "Golang" is present
	contains := strings.Contains(str, "Golang")

	// Print the result
	if contains {
		fmt.Println("The substring 'Golang' is present in the string.")
	} else {
		fmt.Println("The substring 'Golang' is not present in the string.")
	}
}

Output:

The substring 'Golang' is present in the string.

Checking for Substrings in User Input

You can use strings.Contains to verify if a specific word or phrase exists in user input.

Example

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	// Prompt the user to enter a sentence
	fmt.Print("Enter a sentence: ")
	input, _ := reader.ReadString('\n')
	input = strings.TrimSpace(input)

	// Check if the word "Go" is present in the input
	if strings.Contains(input, "Go") {
		fmt.Println("The sentence contains the word 'Go'.")
	} else {
		fmt.Println("The sentence does not contain the word 'Go'.")
	}
}

Console Input/Output:

Enter a sentence: I am learning Go programming.
The sentence contains the word 'Go'.

Real-World Use Case

Filtering Log Messages

In real-world applications, strings.Contains can be used to filter log messages based on specific keywords.

Example

package main

import (
	"fmt"
	"strings"
)

func main() {
	// Define a list of log messages
	logs := []string{
		"INFO: Application started",
		"WARNING: Low memory",
		"ERROR: Unable to connect to database",
		"INFO: User login successful",
	}

	// Filter and print only the log messages that contain the keyword "ERROR"
	fmt.Println("Error log messages:")
	for _, log := range logs {
		if strings.Contains(log, "ERROR") {
			fmt.Println(log)
		}
	}
}

Output:

Error log messages:
ERROR: Unable to connect to database

Conclusion

The strings.Contains function is a simple and efficient way to check for the presence of a substring within a string in Go. It is particularly useful for tasks that involve string searching, validation, and filtering. By using strings.Contains, you can easily determine whether specific text is present in your Go programs, making it a valuable function for handling string data.

Leave a Comment

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

Scroll to Top