Función strings.SplitN() en Golang con ejemplos

strings.SplitN() Function() es una función de manipulación de strings en el lenguaje Go. Se utiliza para dividir una string determinada en substrings separadas por un separador. Esta función devuelve los segmentos de todas las substrings entre esos separadores.

Sintaxis:

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

Aquí, s es la string y sep es el separador. Si s no contiene el sep dado y el sep no está vacío, devolverá un segmento de longitud 1 que contiene solo s. O si la separación está vacía, se dividirá después de cada secuencia UTF-8. O si tanto s como sep están vacíos, devolverá un segmento vacío.

Aquí, el último parámetro determina el número de strings que devolverá la función. Puede ser cualquiera de los siguientes:

  • n es igual a cero (n == 0): el resultado es nulo, es decir, cero substrings. Se devuelve una lista vacía.
  • n es mayor que cero (n > 0): se devolverán como máximo n substrings y la última string será el resto sin dividir.
  • n es menor que cero (n < 0): se devolverán todas las substrings posibles.

Ejemplo 1:

// Golang program to illustrate the
// strings.SplitN() Function
package main
   
import (
    "fmt"
    "strings"
)
   
func main() {
   
    // String s a is comma serparated string
    // The separater used is ","
    // This will split the string into 6 parts
    s := strings.SplitN("a,b,c,d,e,f", ",",6)
    fmt.Println(s)
}

Producción:

[a b c d e f]

Ejemplo 2:

// Golang program to illustrate the
// strings.SplitN() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // String s will be separated by spaces
    // -1 implies all the possible sub strings
    // that can be generated
    s := strings.SplitN("I love GeeksforGeeks portal!", " ", -1)
  
    // This will print all the sub strings
    // of string s in a new line
    for _, v := range s {
        fmt.Println(v)
    }
}

Producción:

I
love
GeeksforGeeks
portal!

Ejemplo 3:

// Golang program to illustrate the
// strings.SplitN() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // This will give empty sub string
    // as 0 is provided as the last parameter
    s := strings.SplitN("a,b,c", ",", 0)
    fmt.Println(s)
  
    // This will give only 3 sub strings
    // a and b will be the first 2 sub strings
    s = strings.SplitN("a:b:c:d:e:f", ":", 3)
    fmt.Println(s)
  
    // Delimiter can be anything
    // a -ve number specifies all sub strings
    s = strings.SplitN("1234x5678x1234x5678", "x", -1)
    fmt.Println(s)
  
    // When the separator is not present in
    // given list, original string is returned
    s = strings.SplitN("qwerty", ",", 6)
    fmt.Println(s)
}

Producción:

[]
[a b c:d:e:f]
[1234 5678 1234 5678]
[qwerty]

Publicación traducida automáticamente

Artículo escrito por vanigupta20024 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *