How to check if a string starts with a substring from an array of substrings in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

// Function to check if a string starts with any substring from the array
func startsWithAny(str string, substrings []string) bool {
    for _, substring := range substrings {
        // Use strings.HasPrefix to check if the string starts with the substring
        if strings.HasPrefix(str, substring) {
            return true
        }
    }
    return false // Return false if no substring matches
}

func main() {
    str := "abcdefg"

    // Array of substrings
    substrings := []string{"xy", "poq", "mnop", "abc", "rsuvw"}

    // Check if the string starts with any substring from the array
    if startsWithAny(str, substrings) {
        fmt.Println("The string starts with a substring from the array.")
    } else {
        fmt.Println("The string does not start with any substring from the array.")
    }
}


/*
run:

The string starts with a substring from the array.

*/

 



answered Apr 4, 2025 by avibootz
...