-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit.go
More file actions
50 lines (35 loc) · 1.19 KB
/
Copy pathsplit.go
File metadata and controls
50 lines (35 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// To execute Go code, please declare a func main() in a package "main"
package main
// # String Split
// Without using a built-in string split method, implement a `split(s, c)` method, which receives a string `s` and a character `c` and splits `s` at each occurrence of `c`, returning a list of strings.
// Example 1: s = "split by space", c = ' '
// Output: ["split", "by", "space"]
// Example 2: s = "beekeeper needed", c = 'e'
// Output: ["b", "", "k", "", "p", "r n", "", "d", "d"]
// Example 3: s = "/home/./..//Documents/", c = '/'
// Output: ["", "home", ".", "..", "", "Documents", ""]
// Example 4: s = "", c = '?'
// Output: []
// Constraints:
// - The length of the input string is at most 10^6
// - The delimiter is a single character
func split(s, delimeter string) []string {
out := []string{}
if len(s) == 0 {
return out
}
// walk the string, checking for the delimiter as we go.
// When we find the delimiter, extract the substring and put it
// into the output array
i, j := 0, 0
for i, j = 0, 0; j < len(s); j++ {
if s[j:j+1] == delimeter {
sub := s[i:j]
out = append(out, sub)
i = j + 1
}
}
// handle the final match
out = append(out, s[i:j])
return out
}