Sling Academy
Home/Golang/Checking Prefixes and Suffixes in Go Strings

Checking Prefixes and Suffixes in Go Strings

Last updated: November 24, 2024

Working with strings is a common task in programming, and one sub-task you might encounter is checking whether a string has a specific prefix or suffix. Go provides straightforward functions to accomplish these tasks. In this article, we'll explore these through examples.

Basic Usage

In Go, the strings package is your go-to package for working with strings. To check prefixes and suffixes, you can use the HasPrefix and HasSuffix functions.

Checking for a Prefix

Let's start by checking if a string starts with a specific prefix. Here's how you can do that:


package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "golang"
    prefix := "go"

    if strings.HasPrefix(str, prefix) {
        fmt.Println("The string starts with the prefix.")
    } else {
        fmt.Println("The string does not start with the prefix.")
    }
}

This will output:

The string starts with the prefix.

Checking for a Suffix

Similarly, you can check whether a string ends with a particular suffix:


package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "golang"
    suffix := "lang"

    if strings.HasSuffix(str, suffix) {
        fmt.Println("The string ends with the suffix.")
    } else {
        fmt.Println("The string does not end with the suffix.")
    }
}

This will output:

The string ends with the suffix.

Intermediate Usage

Once you're comfortable with basic prefix and suffix checking, you can move onto handling more complex cases, like checking multiple prefixes or suffixes.

Checking Multiple Prefixes or Suffixes

When working with multiple prefixes or suffixes, you can use a loop to simplify your conditions:


package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "golang"
    prefixes := []string{"go", "java", "py"}
    suffixes := []string{"lang", "script", "code"}

    for _, prefix := range prefixes {
        if strings.HasPrefix(str, prefix) {
            fmt.Printf("The string starts with the prefix: %s\n", prefix)
        }
    }

    for _, suffix := range suffixes {
        if strings.HasSuffix(str, suffix) {
            fmt.Printf("The string ends with the suffix: %s\n", suffix)
        }
    }
}

This program checks if the string "golang" starts with any of the specified prefixes or ends with any of the specified suffixes, outputting the relevant ones.

Advanced Usage

As you become more familiar with Go and strings, consider optimization approaches, such as concurrent processing, for prefix and suffix checks on larger lists or datasets.

Concurrent Prefix and Suffix Checks

For highly performance-oriented tasks, you might want to concurrently check multiple prefixes or suffixes using Goroutines.


package main

import (
    "fmt"
    "strings"
    "sync"
)

func main() {
    str := "golang"
    prefixes := []string{"go", "java", "py"}
    suffixes := []string{"lang", "script", "code"}

    var wg sync.WaitGroup

    wg.Add(len(prefixes))
    for _, prefix := range prefixes {
        go func(p string) {
            defer wg.Done()
            if strings.HasPrefix(str, p) {
                fmt.Printf("The string starts with the prefix: %s\n", p)
            }
        }(prefix)
    }

    wg.Add(len(suffixes))
    for _, suffix := range suffixes {
        go func(s string) {
            defer wg.Done()
            if strings.HasSuffix(str, s) {
                fmt.Printf("The string ends with the suffix: %s\n", s)
            }
        }(suffix)
    }

    wg.Wait()
}

This example showcases concurrent execution of prefix and suffix checks using Goroutines, making it suitable for handling larger datasets or when you need performance efficiency.

Next Article: String Comparison: Case Sensitivity and Equality in Go

Previous Article: Searching for Substrings in Go: Practical Techniques

Series: Working with Strings in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant