Reputation: 21
I am trying to take an array and split it into an array of strings, this is my code:
if split != "" {
for i := 0; i < len(split); i++ {
for j := 0; j < len(split); j += 0 {
splits := []byte(split)
if splits[i] == ' ' {
result := split[i] - split[j]
for k := 0; k <= i; k++ {
fitting := make([]byte, result)
fitting[k] = splits[k]
fmt.Println(fitting[k])
if k > i-1 {
fittings := string(fitting[:])
word := []string{}
words := append(word, fittings)
fmt.Println(split, words)
}
}
}
}
}
}
return Strings(split)
and this is my test case:
fmt.Println(actual, expected)
for i := 0; i < len(expected); i++ {
if actual[i] != expected[i] {
t.Errorf("does not match")
t.Fail()
}
}
}
None of it is really working.
Upvotes: 0
Views: 7986
Reputation: 56
I just need to know how I could possibly take a string such as "hi li le" and make it into an array of strings such as ["hi","li","le"]
I would like to respond this with simple a simple example:
s := "hi li le"
arr := strings.Split(s, " ")
fmt.Println(arr)
Note: Make sure to import strings & fmt in your package.
Upvotes: 1
Reputation: 165576
I just need to know how I could possibly take a string such as "hi li le" and make it into an array of strings such as ["hi","li","le"]
Yes with strings.Split
or strings.Fields
.
for _, word := range strings.Fields("hi li le") {
fmt.Println(word)
}
Here's a way to do it manually, for illustration.
func split(tosplit string, sep rune) []string {
var fields []string
last := 0
for i,c := range tosplit {
if c == sep {
// Found the separator, append a slice
fields = append(fields, string(tosplit[last:i]))
last = i + 1
}
}
// Don't forget the last field
fields = append(fields, string(tosplit[last:]))
return fields
}
func main() {
str := "hello world stuff"
for _,field := range split(str, ' ') {
fmt.Println(field)
}
}
Upvotes: 7