Golang String Contains Exposed: PRO Tips and Tricks

Written By - admin

Overview of the strings Package in Golang

In the vast world of Golang, the strings package stands out as an essential tool for handling and manipulating sequences of characters. It offers a multitude of functions that make string operations more efficient and easier to implement.

The strings package in Golang is a core part of the standard library. It provides various utility functions designed for the manipulation and evaluation of strings. When dealing with text data, whether you're checking if a particular substring exists (like with "golang string contains"), converting cases, or even splitting the text into slices, this package has got you covered.


Commonly Used Functions from the strings Package

  1. strings.Contains: The star of our discussion, this function checks if a string contains a specified substring.
    • Usage: strings.Contains(s, substr string) bool
    • If you ever find yourself wondering, "How do I check if this Golang string contains a particular substring?", this is your go-to function.
  2. strings.ContainsAny: A variation of strings.Contains, this function checks if a string contains any Unicode code points from another string.
    • Usage: strings.ContainsAny(s, chars string) bool
    • For situations where you're not looking for a specific substring, but any character from a set, this function is a perfect fit. Think of it as a "golang string contains any of these characters" utility.
  3. strings.ContainsRune: Similar to the previous functions, but it checks for a specific rune.
    • Usage: strings.ContainsRune(s string, r rune) bool
    • This is particularly useful when working with individual Unicode characters in a Golang string. Contains a rune? This function has the answer.

While the strings package offers a plethora of other functions like ToLower, ToUpper, Trim, and so on, the above three specifically cater to checking the presence of substrings or characters in a Golang string, making them most relevant to our "golang string contains" agenda.


Deep Dive into strings.Contains Function in Golang

The strings.Contains function is a handy tool within the Golang standard library. As its name suggests, it lets developers ascertain if a string contains a particular substring. For those frequently asking, "Does this Golang string contain my desired substring?", strings.Contains is the ideal function.

1. Signature and Return Values

The signature of strings.Contains is quite simple:

func Contains(s, substr string) bool
  • s: The main string in which you want to search.
  • substr: The substring you are searching for within the main string.
  • Returns: A boolean value (true if the main string contains the substring, false otherwise).

This means if you are trying to determine if a Golang string contains a particular sequence of characters, you'll get a clear yes (true) or no (false) answer.

Here are some basic examples to showcase how to use the strings.Contains function:

2. Checking if "Hello, World!" contains "World":

package main

import (

func main() {
	fmt.Println(strings.Contains("Hello, World!", "World")) // Output: true

This example shows that our Golang string contains the substring "World".

3. Seeing if "golang string contains" contains "python":

package main

import (

func main() {
	fmt.Println(strings.Contains("golang string contains", "python")) // Output: false

Here, the Golang string contains neither snakes nor "python".

4. Case Sensitivity in strings.Contains

One crucial aspect to note about the strings.Contains function is its case sensitivity. The function treats "A" and "a" as distinct characters, which can be both powerful and a potential pitfall.

Checking if "GOLANG String Contains" has "golang":

package main

import (

func main() {
	fmt.Println(strings.Contains("GOLANG String Contains", "golang")) // Output: false

Despite the Golang string containing the word "GOLANG", it returns false because of the difference in case.

An accurate check:

package main

import (

func main() {
	fmt.Println(strings.Contains("GOLANG String Contains", "GOLANG")) // Output: true

This time, our Golang string contains "GOLANG" with the same case, so it returns true.


Comparisons with Other String Functions in Golang

When delving into Golang string manipulation, one realizes there are several functions available to dissect, analyze, and manipulate strings. However, how does our focal point, the strings.Contains function, measure up against its counterparts?


1. strings.Contains vs strings.ContainsAny

strings.Contains: Checks if a Golang string contains a specified substring. The function returns true since our Golang string contains the substring "go".

fmt.Println(strings.Contains("golang string contains", "go")) // Output: true

strings.ContainsAny: Determines if a Golang string contains any Unicode code points (characters) from another string. The function returns false because none of the characters in "zxy" are present in the Golang string "golang string contains".

fmt.Println(strings.ContainsAny("golang string contains", "zxy")) // Output: false

Key Difference: While strings.Contains searches for a full substring, strings.ContainsAny is satisfied with any single matching character.


2. strings.Contains vs strings.HasPrefix and strings.HasSuffix

strings.Contains: Checks if a string contains a specific substring. Clearly, our Golang string contains the term "golang".

fmt.Println(strings.Contains("golang string contains", "golang")) // Output: true

strings.HasPrefix: Evaluates if a Golang string starts with a specific prefix.

fmt.Println(strings.HasPrefix("golang string contains", "golang")) // Output: true

strings.HasSuffix: Assesses if a Golang string ends with a specific suffix.

fmt.Println(strings.HasSuffix("golang string contains", "golang")) // Output: false

Key Difference: While strings.Contains verifies the presence of a substring anywhere in the main string, strings.HasPrefix and strings.HasSuffix check the beginning and end respectively.


3. strings.Contains vs strings.Index and its relevance

strings.Contains: Indicates whether a substring exists. The Golang string contains the word "contains".

fmt.Println(strings.Contains("golang string contains", "contains")) // Output: true

strings.Index: Provides the index of the start of the first instance of a substring. If the substring isn't found, it returns -1.

fmt.Println(strings.Index("golang string contains", "contains")) // Output: 14


Golang string contains Practical Examples

1. Golang string contains (ignoring case):

When users want to perform a case-insensitive search, they typically convert both the main string and the substring to lowercase (or uppercase) and then check for containment.

mainStr := "Golang STRING Contains"
subStr := "STRING"
fmt.Println(strings.Contains(strings.ToLower(mainStr), strings.ToLower(subStr))) // Output: true

By converting both strings to lowercase, we ensure that the "golang string contains" check is case-insensitive. Here, it confirms that "STRING" (regardless of its case) is part of the main string.

2. Golang string contains multiple substrings:

There may be situations where users want to check if a string contains multiple substrings.

mainStr := "Golang string contains multiple words."
subStrs := []string{"Golang", "contains", "words"}
allPresent := true
for _, s := range subStrs {
    if !strings.Contains(mainStr, s) {
        allPresent = false
fmt.Println(allPresent) // Output: true

We're checking if our Golang string contains all the given substrings. In this example, the main string does include all the specified words.

3. Golang string contains a substring:

This is the primary function of strings.Contains — to verify if a string encompasses a particular substring.

fmt.Println(strings.Contains("The core function is to check if a golang string contains a substring.", "substring")) // Output: true

4. Golang string contains a character:

While a single character is technically also a substring, users might specifically think in terms of individual characters.

fmt.Println(strings.Contains("Does this golang string contains the character 'a'?", "a")) // Output: true

At its core, the "golang string contains" function can determine if a specific character is present in a string, since a character is just a substring of length one. In this instance, the main string does have the character 'a'.


Common Mistakes and Gotchas

1. Overlooking Case Sensitivity:

When using the "golang string contains" function, it's imperative to remember that the function is case-sensitive.

fmt.Println(strings.Contains("Golang is Great!", "golang")) // Output: false

The "golang string contains" function will return false in the above example because "Golang" (with an uppercase 'G') and "golang" (all lowercase) are perceived as distinct. Developers often overlook this case-sensitivity, leading to unexpected results.

2. Not Checking for Empty Strings:

An often overlooked aspect is how the "golang string contains" function behaves when given an empty string as the substring.

fmt.Println(strings.Contains("Any string really.", "")) // Output: true

The "golang string contains" function always returns true when checking for an empty substring. This is because, by definition, every string (even an empty one) contains an empty substring. Neglecting this can sometimes lead to unintended outcomes in string processing logic.

3. Misunderstanding the Boolean Return Value:

Some users mistakenly interpret the boolean return value. They assume that true means the string is equal to the substring, rather than containing it.

fmt.Println(strings.Contains("golang", "golang string contains")) // Output: false

A beginner might incorrectly anticipate a true output, thinking both strings are equivalent. However, the "golang string contains" function is checking if the main string (in this case "golang") contains the substring "golang string contains". The function correctly returns false since the main string is actually shorter than the substring and doesn't contain it.


Advanced Tips and Tricks

1. Using strings.Contains in Conjunction with Other strings Functions

Combining the "golang string contains" function with other string manipulation functions can provide powerful and efficient solutions.

Example: Filtering out strings not containing a specific set of substrings:

data := []string{"Golang rules", "Java coffee", "Golang string contains", "Python snake"}
substrs := []string{"Golang", "contains"}
filtered := []string{}

for _, str := range data {
    valid := true
    for _, sub := range substrs {
        if !strings.Contains(str, sub) {
            valid = false
    if valid {
        filtered = append(filtered, str)

fmt.Println(filtered) // Output: ["Golang string contains"]

This example filters an array of strings to only include those where every substring in substrs is present. Using "golang string contains" in tandem with looping constructs offers powerful filtering capabilities.


2. Creating Custom contains Functions for Special Requirements

Sometimes, the standard "golang string contains" might not be adequate for specific needs, like a case-insensitive contains check or a check that takes locale into account.

Example: A case-insensitive contains function:

func containsIgnoreCase(s, substr string) bool {
    return strings.Contains(strings.ToLower(s), strings.ToLower(substr))

fmt.Println(containsIgnoreCase("Golang String Contains", "golang")) // Output: true

By converting both the main string and the substring to lowercase, the custom containsIgnoreCase function effectively conducts a case-insensitive "golang string contains" check.

Example: Contains check for special characters using strings.ContainsRune:

func containsSpecialChar(s string) bool {
    for _, r := range s {
        if !strings.ContainsRune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", r) {
            return true
    return false

fmt.Println(containsSpecialChar("Does this string have * special characters?")) // Output: true

Here, we're creating a custom function that checks if a Golang string contains any characters outside of the defined alphanumeric set. We're leveraging strings.ContainsRune in tandem with range looping for efficient checking.


Testing strings.Contains in Go

Here's how you'd write unit tests for strings.Contains in Go, especially considering mocking and edge cases:

1. Writing Unit Tests Using the testing Package:

Let's start with a simple function that uses "golang string contains" which we will test.

// main.go
package main

import "strings"

func isPresent(mainStr, subStr string) bool {
    return strings.Contains(mainStr, subStr)

Now, let's write a test for this:

// main_test.go
package main

import "testing"

func TestIsPresent(t *testing.T) {
    cases := []struct {
        mainStr, subStr string
        want            bool
        {"Golang string contains is great", "great", true},
        {"Golang string contains is great", "missing", false},
        {"", "missing", false},
        {"Golang", "", true},
        {"", "", true},

    for _, c := range cases {
        got := isPresent(c.mainStr, c.subStr)
        if got != c.want {
            t.Errorf("isPresent(%q, %q) == %v, want %v", c.mainStr, c.subStr, got, c.want)

Here, we've established a series of test cases, including edge cases with empty strings. When testing if "golang string contains" a certain substring, we compare the expected output (want) with the actual output (got) and log errors accordingly.

2. Mocking and Edge Cases:

Mocking isn't typically required when testing functions like strings.Contains directly since it doesn't involve external dependencies. However, if strings.Contains is used within a function that communicates with external systems, you might mock those systems.

For this example, let's consider a hypothetical function that fetches a string from an external source (e.g., a database) and checks if the "golang string contains" a specific keyword.

// main.go
package main

type DataFetcher interface {
    FetchData() string

func containsKeyword(fetcher DataFetcher, keyword string) bool {
    data := fetcher.FetchData()
    return strings.Contains(data, keyword)

Mocking the external system:

// main_test.go
type MockFetcher struct {
    data string

func (m MockFetcher) FetchData() string {
    return m.data

func TestContainsKeyword(t *testing.T) {
    fetcher := MockFetcher{data: "Golang string contains is wonderful"}

    if !containsKeyword(fetcher, "wonderful") {
        t.Error("Expected true for keyword 'wonderful', got false")
    if containsKeyword(fetcher, "absent") {
        t.Error("Expected false for keyword 'absent', got true")

We've defined a DataFetcher interface, which our mock adheres to. This allows us to mimic the behavior of the external system. The test then ensures that the combined behavior of the mock and the "golang string contains" check works as expected.


Can we use Golang string.Contains for Regex Match?

No, strings.Contains in Go does not check for regular expressions. It checks if a string contains another string as a substring in a straightforward manner without interpreting the substring as a regular expression.

If you want to perform regular expression searches within strings in Go, you'd use the regexp package. Here's a basic example of how to use the regexp package:

package main

import (

func main() {
	r, _ := regexp.Compile("a.b") // Matches any string containing "a", any character, then "b".

	fmt.Println(r.MatchString("acb"))     // true
	fmt.Println(r.MatchString("aXb"))     // true
	fmt.Println(r.MatchString("Golang"))  // false

In this example, the regular expression "a.b" matches any string that has an "a", followed by any character, followed by a "b". So, it matches "acb", "aXb", etc.

If you're looking to check for substrings using regular expressions in Go, the regexp package is the way to go.


Frequently Asked Questions

Does strings.Contains check for regex patterns?

No, strings.Contains checks only for direct substring matches. For regex checks, use the regexp package.

Is strings.Contains case-sensitive?

Yes, it is. "ABC" and "abc" are considered different. For a case-insensitive check, you might convert both the string and substring to lowercase (or uppercase) before checking.

How do I check if a string contains any of multiple substrings?

You can loop over your list of substrings and use strings.Contains for each. Alternatively, consider strings.ContainsAny or the regexp package for more complex requirements.

What does strings.Contains return for empty strings?

strings.Contains("anyString", "") will always return true as every string contains an empty substring.

Can I find the position of the substring using strings.Contains?

No, strings.Contains only returns a boolean. Use strings.Index to find the position or -1 if the substring isn't present.

How do I check for a string containing either a prefix or a suffix?

strings.Contains won't help here directly. Use strings.HasPrefix and strings.HasSuffix for these checks.

Is there a performance benefit in using strings.Contains over regex for simple substring checks?

Yes, for simple substring checks, strings.Contains is generally faster and more efficient than using regex, as regex parsing and matching introduces additional overhead.

Can strings.Contains handle multi-line strings or strings with special characters?

Yes, strings.Contains will handle multi-line strings and strings with special characters just like any other strings. No special treatment is required.

How do I check if a string contains a particular character?

You can use strings.ContainsRune(s, r) where s is your string and r is the rune (character) you're checking for.

What's the difference between strings.Contains and strings.ContainsAny?

strings.Contains checks if the string contains a given substring, whereas strings.ContainsAny checks if the string contains any character (rune) from a set of characters.


Conclusion and Best Practices

The strings.Contains function in Go is a powerful and efficient tool for string manipulation. Its simplicity and speed make it a staple for many Go developers when performing substring checks. While its straightforward nature is beneficial, developers must be wary of case sensitivity and the behavior with empty strings. Combining it with other strings package functions can allow for versatile string processing, but always remember that for regular expression needs, one should turn to the regexp package.

Best Practices:

  • Always be aware that strings.Contains is case-sensitive.
  • Remember the behavior with empty strings; any string will always contain an empty substring.
  • For complex substring checks involving multiple substrings or characters, consider looping or combining with other functions from the strings package.
  • Avoid using it for regular expression checks; the regexp package is the right choice for that.


Further Reading Resources


Categories GO

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!