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.

GoData Integrity

Code

gosnippet
24 lines
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

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:`.