Skip to content

strings

O pacote strings implementa funções simples para operar strings codificadas em UTF-8. Em resumo, é um pacote de ferramentas para operar strings.

Documentação oficial: strings package - strings - Go Packages

TIP

Go suporta nativamente caracteres UTF8, e todas as operações de strings são baseadas em UTF8.

Importação

go
import (
   "strings"
)

Abaixo serão explicadas as funções comumente usadas através de exemplos.

Clonar String

go
func Clone(s string) string

Aloca uma nova memória para a cópia. Se uma string vazia for passada, nenhuma memória será alocada e uma string vazia será retornada.

go
func TestClone(t *testing.T) {
   ori := "hello 世界"
   copys := strings.Clone(ori)
   fmt.Println(ori, copys)
   fmt.Println(&ori, &copys)
}
=== RUN   TestClone
hello 世界 hello 世界
0xc00005e5d0 0xc00005e5e0
--- PASS: TestClone (0.00s)
PASS

Comparar Strings

go
func Compare(a, b string) int

Compara a string a com b em ordem lexicográfica. Se a>b, retorna 1; se a<b, retorna -1; se a=b, retorna 0.

go
func TestCompare(t *testing.T) {
  fmt.Println(strings.Compare("abc", "abe"))
  fmt.Println(strings.Compare("abcd", "abe"))
  fmt.Println(strings.Compare("abijk", "abe"))
  fmt.Println(strings.Compare("abe", "abe"))
}
=== RUN   TestCompare
-1
-1
1
0
--- PASS: TestCompare (0.00s)
PASS

Conter String

go
func Contains(s, substr string) bool

Verifica se uma string s contém uma substring substr.

go
func TestContains(t *testing.T) {
  fmt.Println(strings.Contains("abcdefg", "a"))
  fmt.Println(strings.Contains("abcdefg", "abc"))
  fmt.Println(strings.Contains("abcdefg", "ba"))
}
=== RUN   TestContains
true
true
false
--- PASS: TestContains (0.00s)
PASS
go
func ContainsAny(s, chars string) bool

Verifica se qualquer caractere Unicode da string chars está dentro da string s. Em outras palavras, verifica se s contém qualquer caractere de chars.

go
func TestContainsAny(t *testing.T) {
  fmt.Println(strings.ContainsAny("abcedfg", "bac"))
  fmt.Println(strings.ContainsAny("abcedfg", "gfdecba"))
}
=== RUN   TestContainsAny
true
--- PASS: TestContainsAny (0.00s)
PASS
go
func ContainsRune(s string, r rune) bool

Verifica se a string s contém o caractere r.

go
func TestContainsRune(t *testing.T) {
   fmt.Println(strings.ContainsRune("abcedf", 'a'))
   fmt.Println(strings.ContainsRune("abcedf", 'b'))
   fmt.Println(strings.ContainsRune("你好世界", ''))
}
=== RUN   TestContainsRune
true
true
true
--- PASS: TestContainsRune (0.00s)
PASS

Contagem de Ocorrências de Substring

go
func Count(s, substr string) int

Retorna o número de vezes que a substring substr aparece na string s.

go
func TestCount(t *testing.T) {
  fmt.Println(strings.Count("3.1415926", "1"))
  fmt.Println(strings.Count("there is a girl", "e"))
  fmt.Println(strings.Count("there is a girl", ""))
}
=== RUN   TestCount
2
2
16
--- PASS: TestCount (0.00s)
PASS

Remover Substring Especificada

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

Remove a primeira ocorrência da substring sep em s e retorna o resultado após a remoção.

  • before - A string antes da posição da substring removida
  • after - A string depois da posição da substring removida
  • found - Se a substring foi encontrada
go
func TestCut(t *testing.T) {
  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("Hello world", " ")
  show("Hello world", "world")
  show("Hello world", "Hello")
  show("Hello world", "Hello world")
}
=== RUN   TestCut
Cut("Hello world", " ") = "Hello", "world", true
Cut("Hello world", "world") = "Hello ", "", true
Cut("Hello world", "Hello") = "", " world", true
Cut("Hello world", "Hello world") = "", "", true
--- PASS: TestCut (0.00s)
PASS

Igualdade Ignorando Maiúsculas/Minúsculas

go
func EqualFold(s, t string) bool

Retorna se as strings s e t são iguais ignorando maiúsculas/minúsculas.

go
func TestEqualFold(t *testing.T) {
   fmt.Println(strings.EqualFold("你好", "你好"))
   fmt.Println(strings.EqualFold("Hello", "Hello"))
   fmt.Println(strings.EqualFold("Hello", "hELLO"))
}
=== RUN   TestEqualFold
true
true
true
--- PASS: TestEqualFold (0.00s)
PASS

Dividir String

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

O primeiro divide a string por espaços, o segundo usa o valor de retorno da função f para decidir se divide a string.

go
func TestField(t *testing.T) {
   fmt.Printf("%q\n", strings.Fields(" a b c d e f g "))
   fmt.Printf("%q\n", strings.FieldsFunc("a,b,c,d,e,f,g", func(r rune) bool {
      return r == ','
   }))
}
=== RUN   TestField
["a" "b" "c" "d" "e" "f" "g"]
["a" "b" "c" "d" "e" "f" "g"]
--- PASS: TestField (0.00s)
PASS

Buscar Prefixo e Sufixo

go
func HasPrefix(s, prefix string) bool
go
func HasSuffix(s, suffix string) bool

O primeiro busca prefixo, o segundo busca sufixo. Se interessar, você pode ver a implementação do código-fonte aqui, que é bastante engenhosa.

go
func TestPreSuffix(t *testing.T) {
   str := "abbc cbba"
   fmt.Println(strings.HasPrefix(str, "abb"))
   fmt.Println(strings.HasSuffix(str, "bba"))
}
=== RUN   TestPreSuffix
true
true
--- PASS: TestPreSuffix (0.00s)
PASS

Posição da Substring

Retorna o índice da primeira ocorrência da substring:

go
func Index(s, substr string) int

Retorna o índice da primeira ocorrência de qualquer caractere da substring:

go
func IndexAny(s, chars string) int

Retorna o índice da primeira ocorrência do caractere rune:

go
func IndexRune(s string, r rune) int

Exemplo:

go
func TestIndex(t *testing.T) {
   fmt.Println(strings.Index("abcdefg", "bc"))
   fmt.Println(strings.IndexAny("abcdefg", "cb"))
   fmt.Println(strings.IndexRune("abcdefg", 'g'))
}
=== RUN   TestIndex
1
1
6
--- PASS: TestIndex (0.00s)
PASS

Retorna o índice da última ocorrência da substring:

go
func LastIndex(s, substr string) int

Retorna o índice da última ocorrência de qualquer caractere da substring:

go
func LastIndexAny(s, chars string) int

Exemplo:

go
func TestLastIndex(t *testing.T) {
  fmt.Println(strings.LastIndex("abcdefga", "a"))
  fmt.Println(strings.LastIndexAny("abcdefghisa", "ba"))
}

Percorrer e Substituir String

Map retorna uma cópia da string s e modifica todos os caracteres da string s de acordo com a função de mapeamento. Se o mapeamento retornar um valor negativo, o caractere será removido da string sem substituição.

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

Exemplo:

go
func TestMap(t *testing.T) {
   fmt.Println(strings.Map(func(r rune) rune {
      return r - 32
   }, "abcdefghijk"))
   fmt.Println(strings.Map(func(r rune) rune {
      return r + 32
   }, "ABCDEFGHIJK"))
   fmt.Println(strings.Map(func(r rune) rune {
      if r < 'F' {
         return -1
      } else {
         return r
      }
   }, "ABCDEFGHIJK"))
}

Saída:

text
=== RUN   TestMap
ABCDEFGHIJK
abcdefghijk
FGHIJK
--- PASS: TestMap (0.00s)
PASS

Repetir String

Repete a string de acordo com o count fornecido. Se for negativo, causará panic.

go
func Repeat(s string, count int) string

Exemplo:

go
func TestRepeat(t *testing.T) {
   fmt.Println(strings.Repeat("a", 10))
   fmt.Println(strings.Repeat("abc", 10))
}

Saída:

=== RUN   TestRepeat
aaaaaaaaaa
abcabcabcabcabcabcabcabcabcabc
--- PASS: TestRepeat (0.00s)
PASS

Substituir String

s é a string de origem, old é a parte a ser substituída, new é a parte que substitui old, n é o número de substituições. Se n for menor que 0, significa que não há limite no número de substituições.

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

Exemplo:

go
func TestReplace(t *testing.T) {
   fmt.Println(strings.Replace("Hello this is golang", "golang", "c++", 1))
   fmt.Println(strings.Replace("Hello this is golang", "o", "c", -1))
   fmt.Println(strings.Replace("Hello this is golang", "o", "c", 1))
}

Saída:

=== RUN   TestReplace
Hello this is c++
Hellc this is gclang
Hellc this is golang
--- PASS: TestReplace (0.00s)
PASS

Função conveniente do Replace, equivalente a strings.Replace(s, old, new, -1):

go
func ReplaceAll(s, old, new string) string

Exemplo:

go
func TestReplaceAll(t *testing.T) {
  fmt.Println(strings.ReplaceAll("Hello this is golang", "o", "c++"))
}

Saída:

=== RUN   TestReplaceAll
Hellc++ this is gc++lang
--- PASS: TestReplaceAll (0.00s)
PASS

Separar String

Separa a string s em um slice de strings de acordo com a substring sep:

go
func Split(s, sep string) []string

Separa a string s em um slice de strings de acordo com a substring sep, onde o número de separações é determinado por n:

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

Separa a string s em um slice de strings contendo elementos de string com sep de acordo com a substring sep:

go
func SplitAfter(s, sep string) []string

Separa a string s em um slice de strings contendo elementos de string com sep de acordo com a substring sep, onde o número de separações é determinado por n:

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

Exemplo:

go
func TestSplit(t *testing.T) {
   fmt.Printf("%q\n", strings.Split("this is go language", " "))
   fmt.Printf("%q\n", strings.SplitN("this is go language", " ", 2))
   fmt.Printf("%q\n", strings.SplitAfter("this is go language", " "))
   fmt.Printf("%q\n", strings.SplitAfterN("this is go language", " ", 2))
}

Saída:

=== RUN   TestSplit
["this" "is" "go" "language"]
["this" "is go language"]
["this " "is " "go " "language"]
["this " "is go language"]
--- PASS: TestSplit (0.00s)
PASS

Conversão de Maiúsculas/Minúsculas

Converte string em inglês para minúsculas:

go
func ToLower(s string) string

Converte para minúsculas de acordo com o unicode.SpecialCase do idioma correspondente passado:

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

Converte string em inglês para maiúsculas:

go
func ToUpper(s string) string

Converte para maiúsculas de acordo com o unicode.SpecialCase do idioma correspondente passado:

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

Exemplo:

go
func TestLowerAndUpper(t *testing.T) {
   fmt.Println(strings.ToLower("My name is jack,Nice to meet you!"))
   fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Önnek İş"))
   fmt.Println(strings.ToUpper("My name is jack,Nice to meet you!"))
   fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
}

Saída:

=== RUN   TestLowerAndUpper
my name is jack,nice to meet you!
önnek iş
MY NAME IS JACK,NICE TO MEET YOU!
ÖRNEK İŞ
--- PASS: TestLowerAndUpper (0.00s)
PASS

Aparar String

Apara as extremidades da string, removendo qualquer substring que corresponda a cutset:

go
func Trim(s, cutset string) string

Apara a extremidade esquerda da string, removendo qualquer substring que corresponda a cutset:

go
func TrimLeft(s, cutset string) string

Apara o prefixo da extremidade esquerda da string, removendo a substring que corresponde a cutset. Se não corresponder, retorna a string s:

go
func TrimPrefix(s, suffix string) string

Apara a extremidade direita da string, removendo qualquer substring que corresponda a cutset:

go
func TrimRight(s, cutset string) string

Apara o sufixo da extremidade direita da string, removendo a substring que corresponde a cutset. Se não corresponder, retorna a string s:

go
func TrimSuffix(s, suffix string) string

Exemplo:

go
func TestTrim(t *testing.T) {
  fmt.Println(strings.Trim("!!this is a test statement!!", "!!!"))
  fmt.Println(strings.TrimLeft("!!this is a test statement!!", "!!!"))
  fmt.Println(strings.TrimRight("!!this is a test statement!!", "!!!"))
  fmt.Println(strings.TrimPrefix("!!this is a test statement!!", "!!!"))
  fmt.Println(strings.TrimSuffix("!!this is a test statement!!", "!!!"))
}

Saída:

=== RUN   TestTrim
this is a test statement
this is a test statement!!
!!this is a test statement
!!this is a test statement!!
!!this is a test statement!!
--- PASS: TestTrim (0.00s)
PASS

Builder de Strings

O Builder de strings é mais econômico em memória do que operar strings diretamente.

go
type Builder struct {
  // Campos internos não são expostos externamente
}

Exemplo:

go
func TestBuilder(t *testing.T) {
   builder := strings.Builder{}
   builder.WriteString("hello")
   builder.WriteString(" world")
   fmt.Println(builder.Len())
   fmt.Println(builder.String())
}

Saída:

=== RUN   TestBuilder
11
hello world
--- PASS: TestBuilder (0.00s)
PASS

TIP

Não tente passar Builder como valor, por exemplo, ao passar strings.Builder como parâmetro de função, o programa causará panic:

strings: illegal use of non-zero Builder copied by value

Internamente há o seguinte código:

go
type Builder struct {
  addr *Builder // Endereço próprio
  buf  []byte
}

func (b *Builder) copyCheck() {
   if b.addr == nil {
      b.addr = (*Builder)(noescape(unsafe.Pointer(b)))
   } else if b.addr != b {
      panic("strings: illegal use of non-zero Builder copied by value")
   }
}

Ao copiar Builder por valor, também copia o ponteiro do slice interno. Dois Builder estarão operando no mesmo slice ao escrever strings, é por isso que a cópia por valor não é permitida.

Replacer de Strings

Replacer é usado para substituir strings:

go
func NewReplacer(oldnew ...string) *Replacer

Exemplo:

go
func TestReplacer(t *testing.T) {
  r := strings.NewReplacer("<", "<", ">", ">")
  fmt.Println(r.Replace("This is <b>HTML</b>!"))
}

Saída:

This is <b>HTML</b>!

Reader de Strings

Reader implementa as interfaces io.Reader, io.ReaderAt, io.ByteReader, io.ByteScanner, io.RuneReader, io.RuneScanner, io.Seeker e io.WriterTo.

go
func NewReader(s string) *Reader

Exemplo:

go
func TestReader(t *testing.T) {
   reader := strings.NewReader("abcdefghijk")
   buffer := make([]byte, 20, 20)
   read, err := reader.Read(buffer)
   if err != nil {
      log.Panic(err)
   }
   fmt.Println(read)
   fmt.Println(string(buffer))
}

Saída:

=== RUN   TestReader
11
abcdefghijk
--- PASS: TestReader (0.00s)
PASS

Golang por www.golangdev.cn edit