Strings Cut Splits Once With Found Flag
Cut strings at the first separator and peel prefixes or suffixes with CutPrefix and CutSuffix, using the returned boolean instead of hand-rolled index checks.
Code
package main
import (
"fmt"
"strings"
)
func main() {
// Cut:按第一个分隔符切开,found 标记是否命中
host, port, found := strings.Cut("db.internal:5432", ":")
fmt.Println("cut:", host, port, found)
// 未命中时 before 是原串、after 为空
app, env, hit := strings.Cut("billing", "-")
fmt.Println("cut missing:", app, env, hit)
// CutPrefix:剥离前缀,布尔返回是否命中
shard, ok := strings.CutPrefix("shard-07-worker", "shard-")
fmt.Println("prefix:", shard, ok)
// CutSuffix:剥离后缀,适合扩展名处理
base, ok := strings.CutSuffix("report.csv", ".csv")
fmt.Println("suffix:", base, ok)
}Inside the snippet
Strings Cut Splits Once With Found Flag is built around the function main.
Using it
The demo output is labeled (cut:, cut missing:, prefix:), so the printed output reads as a trace of the operations performed.
Key statements
shard, ok := strings.CutPrefix("shard-07-worker", "shard-")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Strings Cut Splits Once With Found Flag print when run?
- The script runs standalone; its 4 labeled outputs include `cut:`, `cut missing:`, `prefix:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.