Substring Checks Contains Prefix Suffix

Check membership in strings with Contains, HasPrefix, HasSuffix, and Count so routing decisions and validations read as declarations instead of index math.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"strings"
)

func route(path string) string {
	switch {
	case strings.HasPrefix(path, "/api/"):
		return "api handler"
	case strings.HasSuffix(path, ".css"):
		return "static css"
	case strings.Contains(path, "health"):
		return "probe"
	default:
		return "fallback"
	}
}

func main() {
	paths := []string{"/api/orders", "/assets/app.css", "/healthz", "/about"}
	for _, p := range paths {
		fmt.Printf("%-16s -> %s\n", p, route(p))
	}

	// Contains 与 Count:包含判断与出现次数
	q := "go/go/go"
	fmt.Println("contains go:", strings.Contains(q, "go"))
	fmt.Println("count go:", strings.Count(q, "go"))

	// 空前缀永远成立——校验逻辑要当心空串参数
	fmt.Println("empty prefix:", strings.HasPrefix("anything", ""))
}

What the code does

Substring Checks Contains Prefix Suffix comes down to the functions route and main.

The file repeats itself only inside for _, p := range paths.

Applying it

Entry signature: func route(path string) string

Running the file prints labeled results such as contains go:, count go:, empty prefix: — each operation’s effect is visible in the output.

The demo flow inside main is route — run the file to see it end to end.

Statements that matter

func route(path string) string {
switch {
case strings.HasPrefix(path, "/api/"):
return "api handler"
case strings.HasSuffix(path, ".css"):
return "static css"
case strings.Contains(path, "health"):
return "probe"
default:
return "fallback"
}
}
for _, p := range paths {
fmt.Printf("%-16s -> %s\n", p, route(p))
}

Interactive Tools for This Topic

FAQ

What does Substring Checks Contains Prefix Suffix print when run?
Run it as a complete program — the output lines carry labels such as `contains go:`, `count go:`, `empty prefix:`.