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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.