Go Reference ยท strings and strconv
Go strings.Cut() function
Reference for Go strings.Cut, CutPrefix and CutSuffix: split a string around the first separator, learn the found flag, and parse key=value pairs safely.
strings.Cut looks for the first occurrence of a separator in a string and returns the text before it, the text after it, and a boolean that says whether the separator was found. It replaces the old pattern of calling strings.Index and then slicing by hand, and it is the neatest way to parse key=value, host:port or name@domain text.
Go 1.20 added two companions: strings.CutPrefix and strings.CutSuffix, which remove a fixed prefix or suffix and tell you whether it was there.
before, after, found := strings.Cut("name=Ada", "=") // before = "name", after = "Ada", found = true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Cut(s, sep string) (before, after string, found bool) func CutPrefix(s, prefix string) (after string, found bool) func CutSuffix(s, suffix string) (before string, found bool)
| Name | Description |
|---|---|
s |
The string to search. |
sep |
The separator. Only its first occurrence in s counts. |
prefix, suffix |
The text to remove from the start or end of s. |
Returns (Cut): the text before the first sep, the text after it, and true. If sep does not occur, it returns s, "", false.
Returns (CutPrefix, CutSuffix): the string without the affix and true, or the unchanged s and false.
Edge cases: an empty sep matches at position 0, so Cut(s, "") returns "", s, true. The package bytes has the same three functions for []byte values.
Usage notes
- Always check
found."novalue"and"empty="both leavevalueempty, but only the second one has a separator. The boolean is how you tell them apart. - Only the first separator splits. In
role=engineer=leadthe value isengineer=lead. Usestrings.SplitorSplitNwhen you need every piece. - No allocation. The results are substrings of
sthat share its memory, soCutis cheap. - Case sensitive. For case-insensitive splitting, lower-case a copy first or search with
strings.EqualFoldlogic of your own. - Prefer it over
Indexplus slicing. The manual version needs anif i >= 0check and carefuli+len(sep)arithmetic, which is easy to get wrong. - Use
CutPrefixinstead ofHasPrefix+TrimPrefix. One call does both and avoids comparing twice. - Chaining. To split
user:pass@host:port, cut on@first and then cut each half on:.