Golang Strings: Using the Contains Function | Codabase

Golang Strings: Using the Contains Function

8 Min Read

Golang strings are an essential part of any Go programmer’s toolbox. One common task is checking if a string contains a specified substring. In this blog post, we’ll dive deep into Golang strings and explore how to use the Contains function from the strings package. We will also provide practical examples and discuss some additional functions that can help you work more effectively with strings in Go.

A Quick Introduction to Golang Strings Contains Function

The Contains function in Golang is part of the strings package, and it allows you to check if a given string contains a specified substring. The function returns a boolean value: true if the substring is found, and false otherwise.

Here’s the basic syntax for the Contains function:
strings.Contains(s, substr string) bool
Let’s break this down:

s: The string in which you want to search for the substring.
substr: The substring you’re looking for.
The function returns a bool value that indicates if the substring is present in the given string.

Using the Contains Function: A Practical Example

Let’s look at a simple example of using the Contains function to check if a string contains a specified substring:


package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Welcome to Codabase.io!"
	substr := "Codabase"

	if strings.Contains(s, substr) {
		fmt.Println("The string contains the substring!")
	} else {
		fmt.Println("The string does not contain the substring.")
	}
}

In this example, we import the strings package and use the Contains function to check if the string s contains the substring substr. If it does, we print a message stating that the substring is present. If not, we print a different message.

When you run this example, you’ll see the following output:
The string contains the substring!

Additional String Functions for More Flexibility

The strings package in Golang provides several other useful functions that you can use to work with strings more effectively. Here are a few examples:

strings.HasPrefix: Checks if a string starts with a specified prefix.
strings.HasSuffix: Checks if a string ends with a specified suffix.
strings.Index: Returns the index of the first occurrence of a substring in a string, or -1 if the substring is not present.
strings.Count: Returns the number of non-overlapping instances of a substring in a string.
strings.Replace: Replaces all occurrences of a substring in a string with another substring.
These functions allow you to perform a variety of string manipulation tasks in Golang, making your code more efficient and readable.

Using the Index Function: A Practical Example

Let’s look at an example using the strings.Index function to find the first occurrence of a substring in a string:


package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Learn Golang with Codabase.io!"
	substr := "Codabase"

	index := strings.Index(s, substr)
	if index != -1 {
		fmt.Printf("The substring is found at index %d.\n", index)
	} else {
		fmt.Println("The substring is not found.")
	}
}

In this example, we use the strings.Index function to find the first occurrence of the substring substr in the string s. If the substring is found, we print the index where it starts. If not, we print a message indicating that the substring is not found.

When you run this example, you’ll see the following output:
The substring is found at index 17.

Using the Replace Function: A Practical Example

Now, let’s take a look at an example using the strings.Replace function to replace all occurrences of a substring in a string with another substring:


package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Learn Golang with Codabase.io! Visit Codabase.io for more tutorials!"
	oldSubstr := "Codabase"
	newSubstr := "MyCodeBase"

	replaced := strings.Replace(s, oldSubstr, newSubstr, -1)
	fmt.Println(replaced)
}

In this example, we use the strings.Replace function to replace all occurrences of the substring oldSubstr with the substring newSubstr in the string s. We pass -1 as the last argument to indicate that we want to replace all occurrences of the substring.

When you run this example, you’ll see the following output:
Learn Golang with MyCodeBase.io! Visit MyCodeBase.io for more tutorials!

FAQ: Common Questions About Golang Strings Contains Function

Is there a case-insensitive version of Contains in Golang?

While there isn’t a dedicated case-insensitive version of the Contains function, you can achieve case-insensitive string comparison by converting both the string and the substring to either uppercase or lowercase using the strings.ToLower or strings.ToUpper functions. For example:


if strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {
    fmt.Println("The string contains the substring (case-insensitive)!")
} else {
    fmt.Println("The string does not contain the substring (case-insensitive).")
}

This approach ensures that the comparison is case-insensitive, as both the string and the substring are converted to the same case before calling the Contains function.

Can I use the Contains function with a slice of strings?

The Contains function is designed to work with individual strings, not slices of strings. However, you can iterate through a slice of strings and use the Contains function on each element. Here’s an example:


slice := []string{"apple", "banana", "cherry"}
substr := "an"

for _, str := range slice {
	if strings.Contains(str, substr) {
		fmt.Printf("The string '%s' contains the substring '%s'.\n", str, substr)
	} else {
		fmt.Printf("The string '%s' does not contain the substring '%s'.\n", str, substr)
	}
}

When you run this example, you’ll see the following output:

The string 'apple' does not contain the substring 'an'.
The string 'banana' contains the substring 'an'.
The string 'cherry' does not contain the substring 'an'.

In conclusion, Golang strings provide a robust and flexible way to work with text data. The Contains function, along with other helpful functions in the strings package, makes it easy to manipulate and search for substrings within strings. With these powerful tools, you’ll be able to tackle a wide variety of string-related tasks in your Go programs, making your code more efficient, readable, and maintainable.

Further Reading

If you’d like to explore more about Golang strings and related functions, here are some resources to help you get started:

  1. Official Golang Strings Package Documentation: Comprehensive documentation for the strings package, including a list of all available functions and their descriptions.
  2. Effective Go: Strings: This section of the “Effective Go” document provides a great overview of strings in Golang and how to work with them efficiently.
  3. Go By Example: String Functions: A collection of examples demonstrating various string functions in the strings package, with accompanying explanations and code samples.

By mastering the Contains function and other string manipulation functions in Golang, you’ll be well-equipped to create efficient and powerful Go programs that handle text data with ease. Happy coding!

Share this Article
Leave a comment