Created
June 9, 2025 18:48
-
-
Save senapk/965b0f63e57e570a45a4c115e4aea198 to your computer and use it in GitHub Desktop.
Strings em Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bufio" | |
| "fmt" | |
| "os" | |
| "strings" | |
| "unicode" | |
| ) | |
| func main() { | |
| // textos são sequências de caracteres | |
| if false { | |
| var texto1 string = "mundo" | |
| var texto2 string = "pé" //p(1) é(2) | |
| fmt.Printf("%s (%d)\n", texto1, len(texto1)) | |
| fmt.Printf("%v (%d)\n", texto2, len(texto2)) | |
| // len() retorna o número de bytes, não de caracteres | |
| } | |
| // Caracteres são internamente números inteiros | |
| if false { | |
| var letra byte = 'A' | |
| // byte é um alias para uint8 | |
| // bytes são números de 0 a 255 | |
| fmt.Printf("%c %v\n", letra, letra) | |
| var unicode rune = 'é' // int32 que é o máximo que um unicode pode ter | |
| fmt.Printf("%c %v\n", unicode, unicode) | |
| // Caracteres são números e podem ser convertidos em ambas direções | |
| fmt.Printf("%c %d\n", 65, 65) // 'A' é 65 na tabela ASCII | |
| fmt.Printf("%c %d\n", 'A'+1, 'A'+1) // 'é' é 233 na tabela Unicode | |
| } | |
| // Fazendo um loop com caracteres | |
| if false { | |
| fmt.Println("Caracteres ASCII:") | |
| for i := '0'; i < 256; i++ { | |
| fmt.Printf("'%c', ", i) // Imprime todos os caracteres ASCII | |
| if i%16 == 0 { // Quebra a linha a cada 16 caracteres | |
| fmt.Println() | |
| } | |
| } | |
| fmt.Println("\nFim do loop de caracteres ASCII") | |
| } | |
| // Percorrimento | |
| if false { | |
| var texto string = "Olá, mundo! 123" | |
| for i, c := range texto { | |
| fmt.Printf("Idx: %d, Char: '%c', Cod: %d\n", i, c, c) | |
| } | |
| } | |
| // Só números | |
| if false { | |
| var telefone string = "(85) 91234-5678" | |
| for _, c := range telefone { | |
| if c >= '0' && c <= '9' { | |
| fmt.Printf("Caractere numérico: '%c'\n", c) | |
| } | |
| } | |
| } | |
| // Concatenando caracteres | |
| if false { | |
| var texto string = "Eu" | |
| texto += " sou" | |
| texto += " Goku" | |
| fmt.Println(texto) // Imprime: Eu sou Goku | |
| var pontuacao byte = '!' | |
| var unicode rune = '✅' | |
| texto += string(pontuacao) // Converte byte para string | |
| texto += string(unicode) // Converte rune para string | |
| fmt.Println(texto) // Imprime: Eu sou Goku!✅ | |
| } | |
| // Pegando só os minúsculos | |
| if false { | |
| var texto string = "Eu sou Goku!" | |
| var minusculos string = "" | |
| for _, c := range texto { | |
| if c >= 'a' && c <= 'z' { | |
| minusculos += string(c) // Converte rune para string | |
| } | |
| } | |
| fmt.Println("Minúsculos:", minusculos) // Imprime: Minúsculos: souoku | |
| } | |
| // Uma forma eficiente de construir strings | |
| if false { | |
| var texto string = "Eu sou Goku" | |
| var builder strings.Builder // Usando strings.Builder para construir strings de forma eficiente | |
| for _, c := range texto { | |
| if c >= 'a' && c <= 'z' { | |
| builder.WriteRune(c) // Adiciona o caractere ao builder | |
| } | |
| } | |
| minusculos := builder.String() // Converte o builder para string | |
| fmt.Println("Minúsculos:", minusculos) // Imprime: Minúsculos: souoku | |
| } | |
| // Sua próprias funções de manipulação de caracteres ou funções prontas da biblioteca strings e unicode | |
| if false { | |
| isLower := func(c rune) bool { | |
| return c >= 'a' && c <= 'z' | |
| } | |
| isUpper := func(c rune) bool { | |
| return c >= 'A' && c <= 'Z' | |
| } | |
| isNumber := func(c rune) bool { | |
| return c >= '0' && c <= '9' | |
| } | |
| isVowel := func(c rune) bool { | |
| return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || | |
| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' | |
| } | |
| toUpper := func(c rune) rune { | |
| if isLower(c) { | |
| return c - ('a' - 'A') // Converte minúsculo para maiúsculo | |
| } | |
| return c | |
| } | |
| fmt.Println(isLower('a')) // true | |
| fmt.Println(isUpper('A')) // true | |
| fmt.Println(isNumber('5')) // true | |
| fmt.Println(isVowel('e')) // true | |
| fmt.Printf("%c\n", toUpper('b')) // B | |
| fmt.Println(unicode.IsUpper('A')) // true | |
| fmt.Println(unicode.IsLower('a')) // true | |
| fmt.Println(unicode.IsDigit('5')) // true | |
| fmt.Println(unicode.IsLetter('é')) // true | |
| fmt.Println(unicode.IsSpace(' ')) // true | |
| fmt.Println(unicode.IsPunct('!')) // true | |
| fmt.Println(strings.ToUpper("olá")) // Converte string para maiúsculo | |
| fmt.Println(strings.ToLower("OLÁ")) // Converte string para minúsculo | |
| } | |
| // Conversão de e para listas de caracteres | |
| if false { | |
| var texto string = "Olá, mundo!" | |
| var listaDeCaracteres []rune // Slice de runes (caracteres Unicode) | |
| // Convertendo string para slice de runes | |
| for _, c := range texto { | |
| listaDeCaracteres = append(listaDeCaracteres, c) | |
| } | |
| fmt.Println("Lista de caracteres:", listaDeCaracteres) // Imprime os códigos dos caracteres | |
| // Convertendo slice de runes de volta para string | |
| textoConvertido := string(listaDeCaracteres) | |
| fmt.Println("Texto convertido:", textoConvertido) // Imprime: Olá, mundo! | |
| } | |
| // usando construtor de lista de caracteres e modificando elementos da lista | |
| if false { | |
| var texto string = "xhulé" | |
| var lista []rune = []rune(texto) // Converte string para slice de runes | |
| fmt.Println("Mostrando lista :", lista) // Imprime os códigos dos caracteres | |
| lista[0] = 'C' // Modifica o primeiro caractere | |
| lista = append(lista, '!') // Adiciona caracteres ao final da lista | |
| lista = lista[:5] | |
| fedido := []rune(" fedido") | |
| lista = append(lista, fedido...) | |
| fmt.Println("Texto convertido:", string(lista)) // Converte slice de runes de volta para string | |
| } | |
| // Lendo palavras individualmente | |
| if false { | |
| fmt.Println("Qual o seu nome?") | |
| var nome string | |
| fmt.Scan(&nome) // Lê uma palavra (até o primeiro espaço) | |
| fmt.Println("Olá,", nome) | |
| fmt.Println("Qual o seu sobrenome?") | |
| var sobrenome string | |
| fmt.Scanln(&sobrenome) // Lê outra palavra (até o primeiro espaço) | |
| fmt.Println("Olá,", nome, sobrenome) | |
| fmt.Println("Qual o seu nome completo?") | |
| // agora lascou! | |
| } | |
| // Lendo uma linha inteira | |
| if false { | |
| scanner := bufio.NewScanner(os.Stdin) | |
| fmt.Println("Qual o seu nome completo?") | |
| scanner.Scan() // Lê uma linha inteira | |
| nomeCompleto := scanner.Text() // Obtém o texto lido | |
| fmt.Println("Olá,", nomeCompleto) | |
| } | |
| // Lendo enquanto houver linhas | |
| if false { | |
| scanner := bufio.NewScanner(os.Stdin) | |
| for scanner.Scan() { // Lê uma linha inteira | |
| linha := scanner.Text() // Obtém o texto lido | |
| fmt.Println(linha) | |
| } | |
| } | |
| // Não misture Scanner com fmt.Scan | |
| if false { | |
| // 1a: linha: quantidade de frases e o texto para procurar | |
| // próximas linhas: frases | |
| scanner := bufio.NewScanner(os.Stdin) | |
| scanner.Scan() // Lê a primeira linha | |
| linha := scanner.Text() | |
| var n int | |
| var texto string | |
| fmt.Sscan(linha, &n, &texto) // Lê a quantidade de frases e o texto | |
| for range n { | |
| scanner.Scan() // Lê cada frase | |
| frase := scanner.Text() | |
| if strings.Contains(frase, texto) { | |
| fmt.Println("Achei") // Imprime a frase que contém o texto | |
| } else { | |
| fmt.Println("Não achei") // Imprime a frase que não contém o texto | |
| } | |
| } | |
| } | |
| // Principais funções de strings | |
| if false { | |
| // Substring | |
| var texto string = "Eu sou Goku" | |
| fmt.Println("Substring:", texto[3:6]) // Imprime: "sou" | |
| // Tamanho | |
| fmt.Println("Tamanho:", len(texto)) // Imprime: 12 | |
| // Se tiver unicode | |
| var unicodeTexto string = "Olá, mundo! 123" | |
| fmt.Println("Tamanho com unicode:", len([]rune(unicodeTexto))) // Imprime: 13 (conta os caracteres Unicode) | |
| // Verifica se contém uma substring | |
| fmt.Println("Contém 'Goku':", strings.Contains(texto, "Goku")) // Imprime: true | |
| // Verifica se começa com uma substring | |
| fmt.Println("Começa com 'Eu':", strings.HasPrefix(texto, "Eu")) // Imprime: true | |
| // Verifica se termina com uma substring | |
| fmt.Println("Termina com 'Goku':", strings.HasSuffix(texto, "Goku")) // Imprime: true | |
| // Quebra em slice de strings | |
| var palavras []string = strings.Split(texto, " ") // Divide o texto em palavras | |
| fmt.Println("Palavras:", palavras) // Imprime: ["Eu", "sou", "Goku"] | |
| // Junta slice de strings em uma única string | |
| var frase string = strings.Join(palavras, ", ") // Junta as palavras com vírgula | |
| fmt.Println("Frase:", frase) // Imprime: "Eu, sou, Goku" | |
| // Substitui uma substring por outra | |
| var frase2 string = "Eu sou Goku, o único Goku que existe" | |
| frase2 = strings.ReplaceAll(frase2, "Goku", "Vegeta") // Substitui todas as ocorrências de "Goku" por "Vegeta" | |
| fmt.Println("Frase substituída:", frase2) // Imprime: "Eu sou Vegeta, o único Vegeta que existe" | |
| } | |
| // replace manual | |
| if false { | |
| var texto string = "Eu sou Goku, o único Goku que existe" | |
| var textoSubstituido string = "" | |
| var textoParaSubstituir string = "Goku" | |
| var textoSubstituto string = "Vegeta" | |
| for i := 0; i < len(texto); i++ { | |
| if strings.HasPrefix(texto[i:], textoParaSubstituir) { | |
| textoSubstituido += textoSubstituto | |
| i += len(textoParaSubstituir) - 1 // Pula o tamanho do texto para substituir | |
| } else { | |
| textoSubstituido += string(texto[i]) | |
| } | |
| } | |
| fmt.Println("Texto substituído:", textoSubstituido) // Imprime: "Eu sou Vegeta, o único Vegeta que existe" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment