Home > OS >  Separating words from a string to a []string
Separating words from a string to a []string

Time:02-12

I am trying to separate each word in a string to a []string. So far, I have wrote this code:

package main

import "fmt"

func main() {
    separate("Splitting words from a phrase.")
}

func separate(s string) {

    spaces := 0
    startword := 0

    for _, v := range s {
        if v == ' ' {
            spaces  

        }
    }

    words := make([]string, spaces 1)
    count := 0

    for x, v := range s {

        if v == ' ' {
            words[count] = s[startword:x]
            count  
            startword = x   1

        }

    }

    s = s[startword:len(s)]
    words[count] = s

    fmt.Printf("%#v\n", words)

}

The output is:

[]string{"Splitting", "words", "from", "a", "phrase."}

If I add another space between two words (Splitting words), the output is:

[]string{"Splitting", "", "words", "from", "a", "phrase."}

What can I add to the code in a way that I don't include any blank string in the slice?

Thank you!

CodePudding user response:

You are reinventing the wheel. It's (more or less) a one-liner:

import "regexp" // Needed to use regex Split

re := regexp.MustCompile("  ")
words := re.Split(s, -1)

The split regex is one or more spaces.

CodePudding user response:

see: https://pkg.go.dev/strings#Split


package main

import (
    "fmt"
    "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"))
}

  • Related