strings

package
v1.26.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

stringsパッケージは、UTF-8エンコードされた文字列を操作するための シンプルな関数を実装します。

GoにおけるUTF-8文字列の情報については、https://blog.golang.org/strings を参照してください。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Clone added in v1.18.0

func Clone(s string) string

Cloneは、sの新しいコピーを返します。 sを新しい割り当てにコピーすることを保証します。 これは、大きな文字列の小さなサブストリングのみを保持する場合に重要な場合があります。 Cloneを使用することで、このようなプログラムがより少ないメモリを使用できるようになります。 もちろん、Cloneを使用するとコピーが作成されるため、Cloneの過剰使用はプログラムのメモリ使用量を増やす可能性があります。 Cloneは通常、プロファイリングによって必要であることが示された場合にのみ使用する必要があります。 長さがゼロの文字列の場合、文字列 "" が返され、割り当ては行われません。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unsafe"
)

func main() {
	s := "abc"
	clone := strings.Clone(s)
	fmt.Println(s == clone)
	fmt.Println(unsafe.StringData(s) == unsafe.StringData(clone))
}
Output:
true
false

func Compare added in v1.5.0

func Compare(a, b string) int

Compareは、2つの文字列を辞書順で比較して整数を返します。 a == bの場合は0、a < bの場合は-1、a > bの場合は+1になります。

3つの比較を行う必要があるとき(例えば、slices.SortFunc と一緒に)にCompareを使用します。 通常、組み込みの文字列比較演算子 ==、<、>などを使用する方が明確で、常に高速です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.Compare("a", "b"))
	fmt.Println(strings.Compare("a", "a"))
	fmt.Println(strings.Compare("b", "a"))
}
Output:
-1
0
1

func Contains

func Contains(s, substr string) bool

Containsは、substrがs内に含まれているかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.Contains("seafood", "foo"))
	fmt.Println(strings.Contains("seafood", "bar"))
	fmt.Println(strings.Contains("seafood", ""))
	fmt.Println(strings.Contains("", ""))
}
Output:
true
false
true
true

func ContainsAny

func ContainsAny(s, chars string) bool

ContainsAnyは、chars内の任意のUnicodeコードポイントがs内に含まれているかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.ContainsAny("team", "i"))
	fmt.Println(strings.ContainsAny("fail", "ui"))
	fmt.Println(strings.ContainsAny("ure", "ui"))
	fmt.Println(strings.ContainsAny("failure", "ui"))
	fmt.Println(strings.ContainsAny("foo", ""))
	fmt.Println(strings.ContainsAny("", ""))
}
Output:
false
true
true
true
false
false

func ContainsFunc added in v1.21.0

func ContainsFunc(s string, f func(rune) bool) bool

ContainsFuncは、s内の任意のUnicodeコードポイントrがf(r)を満たすかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	f := func(r rune) bool {
		return r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u'
	}
	fmt.Println(strings.ContainsFunc("hello", f))
	fmt.Println(strings.ContainsFunc("rhythms", f))
}
Output:
true
false

func ContainsRune

func ContainsRune(s string, r rune) bool

ContainsRuneは、Unicodeコードポイントrがs内に含まれているかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	// 文字列が特定のUnicodeコードポイントを含むかどうかを検索します。
	// たとえば、小文字の"a"のコードポイントは97です。
	fmt.Println(strings.ContainsRune("aardvark", 97))
	fmt.Println(strings.ContainsRune("timeout", 97))
}
Output:
true
false

func Count

func Count(s, substr string) int

Countは、s内の重複しないsubstrのインスタンス数を数えます。 substrが空の文字列の場合、Countはs内のUnicodeコードポイントの数に1を加えたものを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.Count("cheese", "e"))
	fmt.Println(strings.Count("five", "")) // before & after each rune
}
Output:
3
5

func Cut added in v1.18.0

func Cut(s, sep string) (before, after string, found bool)

最初の sep のインスタンスを中心に s をスライスし、 sep の前と後のテキストを返します。 found は、sep が s に現れるかどうかを報告します。 sep が s に現れない場合、cut は s、""、false を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	show := func(s, sep string) {
		before, after, found := strings.Cut(s, sep)
		fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
	}
	show("Gopher", "Go")
	show("Gopher", "ph")
	show("Gopher", "er")
	show("Gopher", "Badger")
}
Output:
Cut("Gopher", "Go") = "", "pher", true
Cut("Gopher", "ph") = "Go", "er", true
Cut("Gopher", "er") = "Goph", "", true
Cut("Gopher", "Badger") = "Gopher", "", false

func CutPrefix added in v1.20.0

func CutPrefix(s, prefix string) (after string, found bool)

CutPrefix は、指定された先頭接頭辞文字列を除いた s を返し、接頭辞が見つかったかどうかを報告します。 s が prefix で始まらない場合、CutPrefix は s、false を返します。 prefix が空の文字列の場合、CutPrefix は s、true を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	show := func(s, prefix string) {
		after, found := strings.CutPrefix(s, prefix)
		fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)
	}
	show("Gopher", "Go")
	show("Gopher", "ph")
}
Output:
CutPrefix("Gopher", "Go") = "pher", true
CutPrefix("Gopher", "ph") = "Gopher", false

func CutSuffix added in v1.20.0

func CutSuffix(s, suffix string) (before string, found bool)

CutSuffix は、指定された末尾接尾辞文字列を除いた s を返し、接尾辞が見つかったかどうかを報告します。 s が suffix で終わらない場合、CutSuffix は s、false を返します。 suffix が空の文字列の場合、CutSuffix は s、true を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	show := func(s, suffix string) {
		before, found := strings.CutSuffix(s, suffix)
		fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)
	}
	show("Gopher", "Go")
	show("Gopher", "er")
}
Output:
CutSuffix("Gopher", "Go") = "Gopher", false
CutSuffix("Gopher", "er") = "Goph", true

func EqualFold

func EqualFold(s, t string) bool

EqualFoldは、UTF-8文字列として解釈されたsとtが、単純なUnicodeの大文字小文字を区別しない比較において等しいかどうかを報告します。 これは、大文字小文字を区別しない形式の大文字小文字を区別しない性質です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.EqualFold("Go", "go"))
	fmt.Println(strings.EqualFold("AB", "ab")) // 単純なケースフォールディングを使用した比較のためtrue
	fmt.Println(strings.EqualFold("ß", "ss"))  // 完全なケースフォールディングを使用しないためfalse
}
Output:
true
true
false

func Fields

func Fields(s string) []string

Fieldsは、[unicode.IsSpace]で定義される1つ以上連続した空白文字ごとに文字列sを分割し、 sの部分文字列のスライスまたはsが空白のみの場合は空のスライスを返します。 返されるスライスの各要素は空ではありません。Split とは異なり、 先頭と末尾の空白文字の並びは破棄されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
}
Output:
Fields are: ["foo" "bar" "baz"]

func FieldsFunc

func FieldsFunc(s string, f func(rune) bool) []string

FieldsFuncは、Unicodeコードポイントcがf(c)を満たす連続部分ごとに文字列sを分割し、 sの部分文字列のスライスを返します。sのすべてのコードポイントがf(c)を満たす場合や 文字列が空の場合、空のスライスを返します。返されるスライスの各要素は空ではありません。 [SplitFunc]とは異なり、先頭と末尾のf(c)を満たす部分は破棄されます。

FieldsFuncは、f(c)を呼び出す順序について保証せず、fが常に同じ値を返すことを前提としています。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	f := func(c rune) bool {
		return !unicode.IsLetter(c) && !unicode.IsNumber(c)
	}
	fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))
}
Output:
Fields are: ["foo1" "bar2" "baz3"]

func FieldsFuncSeq added in v1.25.0

func FieldsFuncSeq(s string, f func(rune) bool) iter.Seq[string]

FieldsFuncSeq returns an iterator over substrings of s split around runs of Unicode code points satisfying f(c). The iterator yields the same strings that would be returned by FieldsFunc(s), but without constructing the slice.

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	text := "The quick brown fox"
	fmt.Println("Split on whitespace(similar to FieldsSeq):")
	for word := range strings.FieldsFuncSeq(text, unicode.IsSpace) {
		fmt.Printf("%q\n", word)
	}

	mixedText := "abc123def456ghi"
	fmt.Println("\nSplit on digits:")
	for word := range strings.FieldsFuncSeq(mixedText, unicode.IsDigit) {
		fmt.Printf("%q\n", word)
	}

}
Output:
Split on whitespace(similar to FieldsSeq):
"The"
"quick"
"brown"
"fox"

Split on digits:
"abc"
"def"
"ghi"

func FieldsSeq added in v1.25.0

func FieldsSeq(s string) iter.Seq[string]

FieldsSeq returns an iterator over substrings of s split around runs of whitespace characters, as defined by unicode.IsSpace. The iterator yields the same strings that would be returned by Fields(s), but without constructing the slice.

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	text := "The quick brown fox"
	fmt.Println("Split string into fields:")
	for word := range strings.FieldsSeq(text) {
		fmt.Printf("%q\n", word)
	}

	textWithSpaces := "  lots   of   spaces  "
	fmt.Println("\nSplit string with multiple spaces:")
	for word := range strings.FieldsSeq(textWithSpaces) {
		fmt.Printf("%q\n", word)
	}

}
Output:
Split string into fields:
"The"
"quick"
"brown"
"fox"

Split string with multiple spaces:
"lots"
"of"
"spaces"

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefixは、文字列sがprefixで始まるかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.HasPrefix("Gopher", "Go"))
	fmt.Println(strings.HasPrefix("Gopher", "C"))
	fmt.Println(strings.HasPrefix("Gopher", ""))
}
Output:
true
false
true

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffixは、文字列sがsuffixで終わるかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.HasSuffix("Amigo", "go"))
	fmt.Println(strings.HasSuffix("Amigo", "O"))
	fmt.Println(strings.HasSuffix("Amigo", "Ami"))
	fmt.Println(strings.HasSuffix("Amigo", ""))
}
Output:
true
false
false
true

func Index

func Index(s, substr string) int

Indexは、s内のsubstrの最初のインスタンスのインデックスを返します。substrがsに存在しない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.Index("chicken", "ken"))
	fmt.Println(strings.Index("chicken", "dmr"))
}
Output:
4
-1

func IndexAny

func IndexAny(s, chars string) int

IndexAnyは、sにcharsの任意のUnicodeコードポイントの最初のインスタンスのインデックスを返します。 charsのUnicodeコードポイントがsに存在しない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.IndexAny("chicken", "aeiouy"))
	fmt.Println(strings.IndexAny("crwth", "aeiouy"))
}
Output:
2
-1

func IndexByte added in v1.2.0

func IndexByte(s string, c byte) int

IndexByteは、s内の最初のcのインスタンスのインデックスを返します。 cがsに存在しない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.IndexByte("golang", 'g'))
	fmt.Println(strings.IndexByte("gophers", 'h'))
	fmt.Println(strings.IndexByte("golang", 'x'))
}
Output:
0
3
-1

func IndexFunc

func IndexFunc(s string, f func(rune) bool) int

IndexFuncは、f(c)がtrueを返す最初のUnicodeコードポイントのインデックスを返します。見つからない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	f := func(c rune) bool {
		return unicode.Is(unicode.Han, c)
	}
	fmt.Println(strings.IndexFunc("Hello, 世界", f))
	fmt.Println(strings.IndexFunc("Hello, world", f))
}
Output:
7
-1

func IndexRune

func IndexRune(s string, r rune) int

IndexRuneは、Unicodeコードポイントrの最初のインスタンスのインデックスを返します。 rがsに存在しない場合は-1を返します。 rが [utf8.RuneError] の場合、無効なUTF-8バイトシーケンスの最初のインスタンスを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.IndexRune("chicken", 'k'))
	fmt.Println(strings.IndexRune("chicken", 'd'))
}
Output:
4
-1

func Join

func Join(elems []string, sep string) string

Joinは、最初の引数の要素を連結して単一の文字列を作成します。区切り文字列sepは、結果の文字列の要素間に配置されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	s := []string{"foo", "bar", "baz"}
	fmt.Println(strings.Join(s, ", "))
}
Output:
foo, bar, baz

func LastIndex

func LastIndex(s, substr string) int

LastIndexは、s内のsubstrの最後のインスタンスのインデックスを返します。 substrがs内に存在しない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.Index("go gopher", "go"))
	fmt.Println(strings.LastIndex("go gopher", "go"))
	fmt.Println(strings.LastIndex("go gopher", "rodent"))
}
Output:
0
3
-1

func LastIndexAny

func LastIndexAny(s, chars string) int

LastIndexAnyは、sにcharsの任意のUnicodeコードポイントの最後のインスタンスのインデックスを返します。 charsのUnicodeコードポイントがsに存在しない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.LastIndexAny("go gopher", "go"))
	fmt.Println(strings.LastIndexAny("go gopher", "rodent"))
	fmt.Println(strings.LastIndexAny("go gopher", "fail"))
}
Output:
4
8
-1

func LastIndexByte added in v1.5.0

func LastIndexByte(s string, c byte) int

LastIndexByteは、sの最後のインスタンスのインデックスを返します。 cがsに存在しない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.LastIndexByte("Hello, world", 'l'))
	fmt.Println(strings.LastIndexByte("Hello, world", 'o'))
	fmt.Println(strings.LastIndexByte("Hello, world", 'x'))
}
Output:
10
8
-1

func LastIndexFunc

func LastIndexFunc(s string, f func(rune) bool) int

LastIndexFuncは、f(c)がtrueを返す最後のUnicodeコードポイントのインデックスを返します。見つからない場合は-1を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Println(strings.LastIndexFunc("go 123", unicode.IsNumber))
	fmt.Println(strings.LastIndexFunc("123 go", unicode.IsNumber))
	fmt.Println(strings.LastIndexFunc("go", unicode.IsNumber))
}
Output:
5
2
-1

func Lines added in v1.25.0

func Lines(s string) iter.Seq[string]

Lines returns an iterator over the newline-terminated lines in the string s. The lines yielded by the iterator include their terminating newlines. If s is empty, the iterator yields no lines at all. If s does not end in a newline, the final yielded line will not end in a newline. It returns a single-use iterator.

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	text := "Hello\nWorld\nGo Programming\n"
	for line := range strings.Lines(text) {
		fmt.Printf("%q\n", line)
	}

}
Output:
"Hello\n"
"World\n"
"Go Programming\n"

func Map

func Map(mapping func(rune) rune, s string) string

Mapは、マッピング関数に従ってすべての文字を変更した文字列sのコピーを返します。 マッピング関数が負の値を返す場合、文字は置換されずに文字列から削除されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	rot13 := func(r rune) rune {
		switch {
		case r >= 'A' && r <= 'Z':
			return 'A' + (r-'A'+13)%26
		case r >= 'a' && r <= 'z':
			return 'a' + (r-'a'+13)%26
		}
		return r
	}
	fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))
}
Output:
'Gjnf oevyyvt naq gur fyvgul tbcure...

func Repeat

func Repeat(s string, count int) string

Repeatは、文字列sのcount個のコピーからなる新しい文字列を返します。

countが負の場合、または(len(s) * count)の結果がオーバーフローする場合、パニックが発生します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println("ba" + strings.Repeat("na", 2))
}
Output:
banana

func Replace

func Replace(s, old, new string, n int) string

Replaceは、古いものの最初のn個の重複しないインスタンスが新しいものに置き換えられた文字列sのコピーを返します。 oldが空の場合、文字列の先頭と各UTF-8シーケンスの後に一致し、kルーン文字列に対してk+1の置換が生成されます。 n < 0の場合、置換の数に制限はありません。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
	fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
}
Output:
oinky oinky oink
moo moo moo

func ReplaceAll added in v1.12.0

func ReplaceAll(s, old, new string) string

ReplaceAllは、古いもののすべての重複しないインスタンスが新しいものに置き換えられた文字列sのコピーを返します。 oldが空の場合、文字列の先頭と各UTF-8シーケンスの後に一致し、kルーン文字列に対してk+1の置換が生成されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo"))
}
Output:
moo moo moo

func Split

func Split(s, sep string) []string

Splitは、sをsepで区切り、それらの区切り文字の間の部分文字列のスライスを返します。

sがsepを含まず、sepが空でない場合、Splitは長さ1のスライスを返します。その唯一の要素はsです。

sepが空の場合、Splitは各UTF-8シーケンスの後に分割します。sとsepの両方が空の場合、Splitは空のスライスを返します。

countが-1の SplitN と同等です。

最初の区切り文字を基準に分割するには、Cut を参照してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Printf("%q\n", strings.Split("a,b,c", ","))
	fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
	fmt.Printf("%q\n", strings.Split(" xyz ", ""))
	fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
}
Output:
["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]

func SplitAfter

func SplitAfter(s, sep string) []string

SplitAfterは、sをsepの後にスライスし、それらの部分文字列のスライスを返します。

sがsepを含まず、sepが空でない場合、SplitAfterは長さ1のスライスを返します。その唯一の要素はsです。

sepが空の場合、SplitAfterは各UTF-8シーケンスの後に分割します。sとsepの両方が空の場合、SplitAfterは空のスライスを返します。

countが-1の SplitAfterN と同等です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))
}
Output:
["a," "b," "c"]

func SplitAfterN

func SplitAfterN(s, sep string, n int) []string

SplitAfterNは、sをsepの後にスライスし、それらの部分文字列のスライスを返します。

countは、返す部分文字列の数を決定します。

  • n > 0:最大n個の部分文字列。最後の部分文字列は区切り文字以降の残りの部分です。
  • n == 0:結果はnil(部分文字列がゼロ個)
  • n < 0:すべての部分文字列

sとsepのエッジケース(空の文字列など)は、SplitAfterのドキュメントで説明されているように処理されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))
}
Output:
["a," "b,c"]

func SplitAfterSeq added in v1.25.0

func SplitAfterSeq(s, sep string) iter.Seq[string]

SplitAfterSeq returns an iterator over substrings of s split after each instance of sep. The iterator yields the same strings that would be returned by SplitAfter(s, sep), but without constructing the slice. It returns a single-use iterator.

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	s := "a,b,c,d"
	for part := range strings.SplitAfterSeq(s, ",") {
		fmt.Printf("%q\n", part)
	}

}
Output:
"a,"
"b,"
"c,"
"d"

func SplitN

func SplitN(s, sep string, n int) []string

SplitNは、sをsepで区切った部分文字列のスライスを返します。

countは、返す部分文字列の数を決定します。

  • n > 0:最大n個の部分文字列。最後の部分文字列は区切り文字以降の残りの部分です。
  • n == 0:結果はnil(部分文字列がゼロ個)
  • n < 0:すべての部分文字列

sとsepのエッジケース(空の文字列など)は、 Split のドキュメントで説明されているように処理されます。

最初の区切り文字を基準に分割するには、Cut を参照してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))
	z := strings.SplitN("a,b,c", ",", 0)
	fmt.Printf("%q (nil = %v)\n", z, z == nil)
}
Output:
["a" "b,c"]
[] (nil = true)

func SplitSeq added in v1.25.0

func SplitSeq(s, sep string) iter.Seq[string]

SplitSeq returns an iterator over all substrings of s separated by sep. The iterator yields the same strings that would be returned by Split(s, sep), but without constructing the slice. It returns a single-use iterator.

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	s := "a,b,c,d"
	for part := range strings.SplitSeq(s, ",") {
		fmt.Printf("%q\n", part)
	}

}
Output:
"a"
"b"
"c"
"d"

func Title deprecated

func Title(s string) string

Titleは、単語の先頭を表すすべてのUnicode文字をUnicodeタイトルケースにマップしたsのコピーを返します。

Deprecated: Titleが単語の境界に使用するルールは、Unicode句読点を適切に処理しません。代わりに、golang.org/x/text/casesを使用してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	// この例をToTitleの例と比較してください。
	fmt.Println(strings.Title("her royal highness"))
	fmt.Println(strings.Title("loud noises"))
	fmt.Println(strings.Title("хлеб"))
}
Output:
Her Royal Highness
Loud Noises
Хлеб

func ToLower

func ToLower(s string) string

ToLowerは、すべてのUnicode文字を小文字にマップしたsを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.ToLower("Gopher"))
}
Output:
gopher

func ToLowerSpecial

func ToLowerSpecial(c unicode.SpecialCase, s string) string

ToLowerSpecialは、Unicode文字をすべて、cで指定されたケースマッピングを使用して小文字にマップしたsのコピーを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Örnek İş"))
}
Output:
örnek iş

func ToTitle

func ToTitle(s string) string

ToTitleは、すべてのUnicode文字をUnicodeタイトルケースにマップしたsのコピーを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	// この例をToTitleの例と比較してください。
	fmt.Println(strings.ToTitle("her royal highness"))
	fmt.Println(strings.ToTitle("loud noises"))
	fmt.Println(strings.ToTitle("хлеб"))
}
Output:
HER ROYAL HIGHNESS
LOUD NOISES
ХЛЕБ

func ToTitleSpecial

func ToTitleSpecial(c unicode.SpecialCase, s string) string

ToTitleSpecialは、Unicode文字をすべて、特別なケースルールに優先してUnicodeタイトルケースにマップしたsのコピーを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Println(strings.ToTitleSpecial(unicode.TurkishCase, "dünyanın ilk borsa yapısı Aizonai kabul edilir"))
}
Output:
DÜNYANIN İLK BORSA YAPISI AİZONAİ KABUL EDİLİR

func ToUpper

func ToUpper(s string) string

ToUpperは、すべてのUnicode文字を大文字にマップしたsを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.ToUpper("Gopher"))
}
Output:
GOPHER

func ToUpperSpecial

func ToUpperSpecial(c unicode.SpecialCase, s string) string

ToUpperSpecialは、Unicode文字をすべて、cで指定されたケースマッピングを使用して大文字にマップしたsのコピーを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
}
Output:
ÖRNEK İŞ

func ToValidUTF8 added in v1.13.0

func ToValidUTF8(s, replacement string) string

ToValidUTF8は、無効なUTF-8バイトシーケンスのランを置換文字列で置き換えたsのコピーを返します。置換文字列は空にすることができます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Printf("%s\n", strings.ToValidUTF8("abc", "\uFFFD"))
	fmt.Printf("%s\n", strings.ToValidUTF8("a\xffb\xC0\xAFc\xff", ""))
	fmt.Printf("%s\n", strings.ToValidUTF8("\xed\xa0\x80", "abc"))
}
Output:
abc
abc
abc

func Trim

func Trim(s, cutset string) string

Trimは、cutsetに含まれるすべての先頭と末尾のUnicodeコードポイントを削除した文字列sのスライスを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Print(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡"))
}
Output:
Hello, Gophers

func TrimFunc

func TrimFunc(s string, f func(rune) bool) string

TrimFuncは、f(c)がtrueを返す最初と最後のUnicodeコードポイントcを含まないように、文字列sの先頭と末尾からすべてのUnicodeコードポイントcを削除したスライスを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Print(strings.TrimFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
	}))
}
Output:
Hello, Gophers

func TrimLeft

func TrimLeft(s, cutset string) string

TrimLeftは、cutsetに含まれるすべての先頭のUnicodeコードポイントを削除した文字列sのスライスを返します。

接頭辞を削除するには、代わりに TrimPrefix を使用してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Print(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡"))
}
Output:
Hello, Gophers!!!

func TrimLeftFunc

func TrimLeftFunc(s string, f func(rune) bool) string

TrimLeftFuncは、f(c)がtrueを返す最初のUnicodeコードポイントcを含まないように、文字列sの先頭からすべてのUnicodeコードポイントcを削除したスライスを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Print(strings.TrimLeftFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
	}))
}
Output:
Hello, Gophers!!!

func TrimPrefix added in v1.1.0

func TrimPrefix(s, prefix string) string

TrimPrefixは、指定された接頭辞文字列を除いたsを返します。 sが接頭辞で始まらない場合、sは変更されずにそのまま返されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	var s = "¡¡¡Hello, Gophers!!!"
	s = strings.TrimPrefix(s, "¡¡¡Hello, ")
	s = strings.TrimPrefix(s, "¡¡¡Howdy, ")
	fmt.Print(s)
}
Output:
Gophers!!!

func TrimRight

func TrimRight(s, cutset string) string

TrimRightは、cutsetに含まれるすべての末尾のUnicodeコードポイントを削除した文字列sのスライスを返します。

接尾辞を削除するには、代わりに TrimSuffix を使用してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Print(strings.TrimRight("¡¡¡Hello, Gophers!!!", "!¡"))
}
Output:
¡¡¡Hello, Gophers

func TrimRightFunc

func TrimRightFunc(s string, f func(rune) bool) string

TrimRightFuncは、f(c)がtrueを返す最後のUnicodeコードポイントcを含まないように、文字列sの末尾からすべてのUnicodeコードポイントcを削除したスライスを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
	"github.com/shogo82148/std/unicode"
)

func main() {
	fmt.Print(strings.TrimRightFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
	}))
}
Output:
¡¡¡Hello, Gophers

func TrimSpace

func TrimSpace(s string) string

TrimSpaceは、Unicodeで定義されるすべての先頭と末尾の空白文字を削除した 文字列sのスライス(部分文字列)を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
Output:
Hello, Gophers

func TrimSuffix added in v1.1.0

func TrimSuffix(s, suffix string) string

TrimSuffixは、指定された接尾辞文字列を除いたsを返します。 sが接尾辞で終わらない場合、sは変更されずにそのまま返されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	var s = "¡¡¡Hello, Gophers!!!"
	s = strings.TrimSuffix(s, ", Gophers!!!")
	s = strings.TrimSuffix(s, ", Marmots!!!")
	fmt.Print(s)
}
Output:
¡¡¡Hello

Types

type Builder added in v1.10.0

type Builder struct {
	// contains filtered or unexported fields
}

Builderは、 Builder.Write メソッドを使用して効率的に文字列を構築するために使用されます。 メモリのコピーを最小限に抑えます。ゼロ値はすぐに使用できます。 非ゼロのBuilderをコピーしないでください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	var b strings.Builder
	for i := 3; i >= 1; i-- {
		fmt.Fprintf(&b, "%d...", i)
	}
	b.WriteString("ignition")
	fmt.Println(b.String())

}
Output:
3...2...1...ignition

func (*Builder) Cap added in v1.12.0

func (b *Builder) Cap() int

Capは、ビルダーの基礎となるバイトスライスの容量を返します。 構築中の文字列に割り当てられた総スペースを含み、すでに書き込まれたバイトも含みます。

func (*Builder) Grow added in v1.10.0

func (b *Builder) Grow(n int)

Growは、必要に応じてbの容量を拡張し、別のnバイトのスペースを保証します。 Grow(n)の後、少なくともnバイトを別の割り当てなしでbに書き込むことができます。 nが負の場合、Growはパニックを引き起こします。

func (*Builder) Len added in v1.10.0

func (b *Builder) Len() int

Lenは、蓄積されたバイト数を返します。b.Len() == len(b.String())です。

func (*Builder) Reset added in v1.10.0

func (b *Builder) Reset()

Resetは、 Builder を空にリセットします。

func (*Builder) String added in v1.10.0

func (b *Builder) String() string

Stringは、蓄積された文字列を返します。

func (*Builder) Write added in v1.10.0

func (b *Builder) Write(p []byte) (int, error)

Writeは、pの内容をbのバッファに追加します。 Writeは常にlen(p)、nilを返します。

func (*Builder) WriteByte added in v1.10.0

func (b *Builder) WriteByte(c byte) error

WriteByteは、バイトcをbのバッファに追加します。 返されるエラーは常にnilです。

func (*Builder) WriteRune added in v1.10.0

func (b *Builder) WriteRune(r rune) (int, error)

WriteRuneは、UnicodeコードポイントrのUTF-8エンコーディングをbのバッファに追加します。 rの長さとnilエラーを返します。

func (*Builder) WriteString added in v1.10.0

func (b *Builder) WriteString(s string) (int, error)

WriteStringは、sの内容をbのバッファに追加します。 sの長さとnilエラーを返します。

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Readerは、文字列から読み取りを行うことで、 io.Readerio.ReaderAtio.ByteReaderio.ByteScannerio.RuneReaderio.RuneScannerio.Seeker 、および io.WriterTo インターフェースを実装します。 Readerのゼロ値は、空の文字列のReaderのように動作します。

func NewReader

func NewReader(s string) *Reader

NewReaderは、sから読み取る新しい Reader を返します。 bytes.NewBufferString に似ていますが、より効率的で書き込み不可能です。

func (*Reader) Len

func (r *Reader) Len() int

Lenは、文字列の未読部分のバイト数を返します。

func (*Reader) Read

func (r *Reader) Read(b []byte) (n int, err error)

Readは、 io.Reader インターフェースを実装します。

func (*Reader) ReadAt

func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

ReadAtは、 io.ReaderAt インターフェースを実装します。

func (*Reader) ReadByte

func (r *Reader) ReadByte() (byte, error)

ReadByteは、 io.ByteReader インターフェースを実装します。

func (*Reader) ReadRune

func (r *Reader) ReadRune() (ch rune, size int, err error)

ReadRuneは、io.RuneReader インターフェースを実装します。

func (*Reader) Reset added in v1.7.0

func (r *Reader) Reset(s string)

Resetは、 Reader をsから読み取るようにリセットします。

func (*Reader) Seek

func (r *Reader) Seek(offset int64, whence int) (int64, error)

Seekは、 io.Seeker インターフェースを実装します。

func (*Reader) Size added in v1.5.0

func (r *Reader) Size() int64

Sizeは、基礎となる文字列の元の長さを返します。 Sizeは、 Reader.ReadAt を介して読み取ることができるバイト数です。 返される値は常に同じであり、他のメソッドの呼び出しに影響を受けません。

func (*Reader) UnreadByte

func (r *Reader) UnreadByte() error

UnreadByteは、 io.ByteScanner インターフェースを実装します。

func (*Reader) UnreadRune

func (r *Reader) UnreadRune() error

UnreadRuneは、 io.RuneScanner インターフェースを実装します。

func (*Reader) WriteTo added in v1.1.0

func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteToは、 io.WriterTo インターフェースを実装します。

type Replacer

type Replacer struct {
	// contains filtered or unexported fields
}

Replacerは、置換物のリストで文字列を置換します。 複数のゴルーチンによる同時使用に対して安全です。

func NewReplacer

func NewReplacer(oldnew ...string) *Replacer

NewReplacerは、古い文字列と新しい文字列のペアのリストから新しい Replacer を返します。 置換は、対象文字列に現れる順序で実行され、重複するマッチングは行われません。 古い文字列の比較は引数の順序で行われます。

NewReplacerは、奇数の引数が与えられた場合にパニックを引き起こします。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/strings"
)

func main() {
	r := strings.NewReplacer("<", "&lt;", ">", "&gt;")
	fmt.Println(r.Replace("This is <b>HTML</b>!"))
}
Output:
This is &lt;b&gt;HTML&lt;/b&gt;!

func (*Replacer) Replace

func (r *Replacer) Replace(s string) string

Replaceは、すべての置換を実行したsのコピーを返します。

func (*Replacer) WriteString

func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)

WriteStringは、すべての置換を実行したsをwに書き込みます。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL