Golang String Contains Exposed: PRO Tips and Tricks


GO

Overview of the strings Package in Golang

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

Strings Package in Golang is a core part of its standard library with various utility functions designed for manipulating and evaluating strings. In case you are dealing with text data whereby checking if there is a particular substring (e.g. “golang string contains”), changing cases or even splitting the text into slices, this package got it all covered.

Here are some of the commonly used functions from the strings Package

  1. strings.Contains: The star of our discussion, it checks if a given string has a specific substring.
    • Usage: strings.Contains(s, substr string) bool
    • Whenever you ask yourself how can I find out whether this Golang string contains my intended substring?, this is what you need to use.
  2. strings.ContainsAny: This function is another variant of strings.Contains that determines if one string includes any Unicode code points from another string.
    • Usage: strings.ContainsAny(s, chars string) bool
    • In situations where you don’t want any specific sub-string but rather any character within a set think about it as “golang string contains any of these characters” utility.
  3. strings.ContainsRune: Same as previous ones but check for specific rune
    • Usage: strings.ContainsRune(s string, r rune) bool
    • This comes in handy when working with individual Unicode characters in a Golang string. Does it contain rune? This function knows it all!

While there are numerous other functions within the strings package like ToLower, ToUpper and Trim among others; there three mentioned above specifically deal with checking for substrings or characters presence inside Go’s String thus making them proximately relevant to our “golang sting contains” agenda.

 

Deep Dive into strings.Contains Function in Golang

In Go, the strings.Contains function is simple and widely used in confirming if a given substring is available in a string. It is among other functions that come with the strings package for use on UTF-8 encoded strings. This function makes it easy to search for specific characters like validating input, checking whether specific words occur or implementing a conditional statement depending on the contents of a string.

The signature of function strings.Contains reads as follows:

func Contains(s, substr string) bool

Here,

  • s refers to the string that needs to be searched.
  • substr contains the sub-string being looked for inside “s”.
  • It returns true if substr is found within “s”.

strings.contains does case-sensitive search checking whether substr exists anywhere within s and return true when substr is found anywhere within s. Hence when substr cannot be seen or it happens that it is an empty string then this method will return false otherwise it returns true as long as substr length remains zero. Note carefully that Anyway if substr length = 0 then whatever may be the situation this method shall always return True since an empty string by convention always qualifies itself to be a substring of any other word.

Here is a basic example to showcase how to use the strings.Contains function:

package main

import (
	"fmt"
	"strings"
)

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

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

 

Comparing strings.Contains with Other String Functions

When one begins to delve into Golang string manipulation, they soon realize that there are many functions available for partitioning dissecting and transforming strings. But how does the function strings.Contains compare with others?

 

1. strings.Contains vs strings.ContainsAny

In Go, strings.Contains and strings.ContainsAny are included in the strings package, and they offer support for verifying if there are any substrings or characters in a given string. However, there are differences between them as they serve various purposes.

strings.Contains: This is used to determine whether a specific substring exists within a larger string. It will return true if it finds the substring and false otherwise. It is case-sensitive.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Contains("hello world", "world")) // true
    fmt.Println(strings.Contains("hello world", "World")) // false, case-sensitive
}

strings.ContainsAny: Check if any of the characters contained in the second argument are present anywhere in the first one. It returns true when at least one match is found and false otherwise. With this function you can easily find out whether or not multiple possible letters exist without having to mind their order or count of occurrence.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.ContainsAny("hello world", "xyz")) // false, none of x, y, z is found
    fmt.Println(strings.ContainsAny("hello world", "hw"))  // true, h is found
    fmt.Println(strings.ContainsAny("hello world", "xyzw")) // true, w is found
}

Key Differences:

  • Purpose: strings.Contains checks for every sub-string while strings.ContainsAny also does that but for any character from some other word.
  • Parameter Type: The second parameter for strings.Contains consists of a substring that must exactly appear once within this text while that of string.ContainsAny contains only set of characters (as string) that will be checked whether at least one such character appears in it.
  • Use Case: Use strings.Contains when your condition depends on the presence of a specific sequence of characters. Use strings.ContainsAny when the condition is satisfied by the presence of any one of several possible characters.

 

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

In Go, the strings package offers diverse functions to manipulate string values like strings.Contains, strings.HasPrefix, and strings.HasSuffix. Various uses of each function in String Analysis:

  • strings.Contains checks if a string contains a specific substring.
  • strings.HasPrefix checks if a string starts with a specific prefix.
  • strings.HasSuffix checks if a string ends with a specific suffix.
package main

import (
    "fmt"
    "strings"
)

func main() {
    baseString := "Hello, World!"

    // strings.Contains: This checks whether any part of the initial text is “World”.
    fmt.Println("Contains 'World'? :", strings.Contains(baseString, "World")) // true

    // strings.HasPrefix: This checks whether the beginning of the original text is “Hello”.
    fmt.Println("Has Prefix 'Hello'? :", strings.HasPrefix(baseString, "Hello")) // true

    // strings.HasSuffix: This determines whether or not the end of the initial text is “World!”.
    fmt.Println("Has Suffix 'World!'? :", strings.HasSuffix(baseString, "World!")) // false, correct suffix is "!"

    // Demonstrates correct usage of HasSuffix
    fmt.Println("Has Suffix '!'? :", strings.HasSuffix(baseString, "!")) // true
}

Key Differences Explained

  • strings.Contains: This function scans through an entire string in order to determine whether or not it has a specified substring in any position. If any part of string contains substring then returns true.
  • strings.HasPrefix: Starting at character zero (0), this method will check if the beginning portion of that character array begins with that particular prefix. Examples where the starting point matters include protocol names in URLs and file extensions.
  • strings.HasSuffix: Instead of reading from left to right as with prefixes discussed above, this method reads from right to left and compares each subsequent item against its corresponding element before going on to compare another two items. It is ideal for file types which are recognizable by their extensions or other similar forms.

 

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

Both strings.Contains and strings.Index are functions in the strings package of Go programming language that help in searching for a particular string but they serve different purposes and give different type of information about the search. For example, strings.Contains checks if one string is inside another string. It has a return value being boolean i.e. true if the substring is found or false otherwise.
And then there is a method called strings.Index which takes a substring and returns an index (starting at 0) to identify first character of first occurrence. If it doesn’t exist, this will return -1.

Consider this Go code snippet illustrating how each function can be used to analyze our base string:

package main

import (
    "fmt"
    "strings"
)

func main() {
    baseString := "Hello, World!"

    // strings.Contains: Checks if the base string contains "World"
    containsWorld := strings.Contains(baseString, "World")
    fmt.Println("Contains 'World'? :", containsWorld) // true

    // strings.Index: Finds the index of "World" in the base string
    indexWorld := strings.Index(baseString, "World")
    fmt.Println("Index of 'World'? :", indexWorld) // 7

    // Attempt to find a substring that does not exist
    indexNotFound := strings.Index(baseString, "XYZ")
    fmt.Println("Index of 'XYZ'? :", indexNotFound) // -1
}

Differences between these two functions as well as their use cases.

For instance, while strings.Contains returns boolean indicating the presence or absence of some substring in a given string—this helps most when dealing with conditionals, String.Index will tell you where exactly your substring can be found.

 

Some practical examples using golang string.Contains

1. Check if 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

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. Check if golang string contains multiple substring

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
        break
    }
}
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. Check if 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 string.Contains function, it is important to remember that it is case-sensitive.

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

In the above example, the output of string.Contains is false. While "Golang" and "golang" are similar, they are not equal. Developers often overlook this fact and expect otherwise because we are so used to modern programming languages being case-insensitive.

2. Not Checking for Empty Strings:

A less common pitfall but still worth mentioning is what happens when you pass an empty string as the substring argument.

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

If an empty string is passed for substring, then Contains will always return true. We can think of it like this: Every single possible substring (even an empty one) exists in every single possible parent string (even an empty one). Many developers forget this quirky feature which sometimes leads to unexpected behavior in their logic!

3. Misunderstanding the Boolean Return Value:

Some people misuse the boolean return value. They believe that a true value means that both strings are equal.

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

If a beginner saw the result of our second test, they might be confused. Although both strings seem to be equivalent at first glance, they aren’t! The main string ("golang") does not contain the substring ("verylongsubstring") since it’s shorter than itself -- sounds confusing doesn't it? But that's how these checks work!

 

Advanced Tips and Tricks

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

Combining the 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
            break
        }
    }
    if valid {
        filtered = append(filtered, str)
    }
}

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

This example filters an array of strings to include only those where every substring in substrs is present.

 

2. Creating Custom contains Functions for Special Requirements

Sometimes, the standard string.Contains function might not be enough. You can’t run a case-insensitive contains check for instance or take 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

You can convert both the main string and the substring to lowercase instead to make it work with custom containsIgnoreCase function.

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 has any characters outside of the alphanumeric set defined by us. We are using strings.ContainsRune and range looping for efficient checking.

 

Can you use Golang string.Contains for Regex Match?

No, in Go string.Contains does not support regex match. It just checks whether one string is contained in another 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 simple example of how this works:

package main

import (
	"fmt"
	"regexp"
)

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.

To check substrings with regular expressions in Go, you would need to use the regexp package.

 

Frequently Asked Questions

Does strings.Contains check for regex patterns?

No, instead it just looks for an exact match of the substring. But for regex checks, use the regexp package.

Is strings.Contains case-sensitive?

Yes, it is. "ABC" and "abc" are considered to be different things. If you want a case-insensitive check, you can 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 each substring in your list and use strings.Contains on them individually. Alternatively, you could consider using strings.ContainsAny or the regexp package instead if that would better suit your needs.

What does strings.Contains return when empty string is passed?

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

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

No, because it only returns a boolean value. But you can use strings.Index() instead which will provide the index position or -1 if not found.

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

Unfortunately you cannot use strings.Contains directly this way. Instead use Prefix() and Suffix() methods specifically created for these cases.

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

Yes there's definitely more performance gain in using strings.Contains instead of Regex for simple substring checks because Regex parsing and matching adds additional overheads which could've been avoided by using Contains.

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

Yes! It handles multi-line and special characters just like any other regular single-line string. So no need to worry about something special here!

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

You can pass the rune (character) as second parameter to Use strings.ContainsRune(s, r) method where s is your original main string which needs to be checked for the character.

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

strings.Contains checks if a given substring is present in the main string. But whereas strings.ContainsAny checks if any character (rune) from a set of characters is present in the main string.

 

Conclusion and Best Practices

Go’s function, strings.Contains is a powerful and efficient tool for working with strings. Its simplicity and fastness makes it a Go developer’s must have when doing substring checks. Simple as it may seem, this comes with its own caveats like being case sensitive or what happens when the string has no characters in it. This can be combined with other functions in the strings package to enable versatile string processing; however, it should be noted that the default one offers little support for regular expressions

Best Practices:

  • Note that strings.Contains is case-sensitive.
  • Remember the behavior with empty strings; an empty string will always contain any string as its substring.
  • Whereas complex substring checks involve more than one character or substrings, looping or using other methods of the package may help.
  • Avoid using it for regular expression checks; The right choice would be regexp package.

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

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!!

Leave a Comment