Has Suffix And Has Prefix Golang

As a software developer who frequently works with Go (Golang), I often come across the need to check whether a string has a certain suffix or prefix. This task may seem simple on the surface, but it’s an essential part of many applications. In this article, I’ll delve into the details of how to determine if a string has a specific suffix or prefix in Golang. Let’s explore this important topic together.

Checking for a Suffix in Golang

When working with strings in Golang, determining if a string has a specific suffix is a common requirement. Fortunately, Golang provides a simple and effective way to accomplish this through the use of the strings.HasSuffix function. This function takes two parameters: the string to be checked and the suffix to search for. It returns a boolean value indicating whether the string ends with the specified suffix. Let’s take a look at a basic example to illustrate its usage:


package main
import (
"fmt"
"strings"
)
func main() {
str := "hello.go"
fmt.Println(strings.HasSuffix(str, ".go")) // Output: true
fmt.Println(strings.HasSuffix(str, ".exe")) // Output: false
}

Checking for a Prefix in Golang

Similarly, Golang provides the strings.HasPrefix function to check if a string has a specific prefix. This function also takes two parameters: the string to be checked and the prefix to look for. It returns a boolean value indicating whether the string starts with the specified prefix. Let’s take a look at an example to demonstrate its usage:


package main
import (
"fmt"
"strings"
)
func main() {
str := "gopher.png"
fmt.Println(strings.HasPrefix(str, "go")) // Output: true
fmt.Println(strings.HasPrefix(str, "java")) // Output: false
}

Combining HasSuffix and HasPrefix

In some cases, we may need to check both the prefix and suffix of a string. Golang makes this task straightforward by providing the strings.TrimPrefix and strings.TrimSuffix functions. These functions remove a specified prefix or suffix from the string if it exists, respectively. We can then use the resulting string to determine if the prefix or suffix was present. Here’s a simple example of how we can combine these functions:


package main
import (
"fmt"
"strings"
)
func main() {
str := "hello_world.txt"
prefixStr := strings.TrimPrefix(str, "hello_")
suffixStr := strings.TrimSuffix(str, ".txt")
fmt.Println(prefixStr) // Output: world.txt
fmt.Println(suffixStr) // Output: hello_world
}

Conclusion

In conclusion, the ability to check for suffixes and prefixes in a string is a fundamental requirement in many programming scenarios. In Golang, the strings.HasSuffix and strings.HasPrefix functions provide a convenient way to perform these checks effectively. Additionally, the strings.TrimSuffix and strings.TrimPrefix functions allow us to manipulate strings based on their prefixes and suffixes. By mastering these string manipulation techniques, we can enhance the robustness and functionality of our Golang applications.