Created
April 24, 2019 15:43
-
-
Save sandacn/c1f35240670d488807ad4dd1b7abf55d to your computer and use it in GitHub Desktop.
split string with fixed size in golang
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 ( | |
"fmt" | |
"strings" | |
"time" | |
"math" | |
) | |
func splitByWidthMake(str string, size int) []string { | |
strLength := len(str) | |
splitedLength := int(math.Ceil(float64(strLength) / float64(size))) | |
splited := make([]string, splitedLength) | |
var start, stop int | |
for i := 0; i < splitedLength; i += 1 { | |
start = i * size | |
stop = start + size | |
if stop > strLength { | |
stop = strLength | |
} | |
splited[i] = str[start : stop] | |
} | |
return splited | |
} | |
func splitByWidth(str string, size int) []string { | |
strLength := len(str) | |
var splited []string | |
var stop int | |
for i := 0; i < strLength; i += size { | |
stop = i + size | |
if stop > strLength { | |
stop = strLength | |
} | |
splited = append(splited, str[i:stop]) | |
} | |
return splited | |
} | |
func splitRecursive(str string, size int) []string { | |
if len(str) <= size { | |
return []string{str} | |
} | |
return append([]string{string(str[0:size])}, splitRecursive(str[size:], size)...) | |
} | |
func main() { | |
/* | |
testStrings := []string{ | |
"hello world", | |
"", | |
"1", | |
} | |
*/ | |
testStrings := make([]string, 10) | |
for i := range testStrings { | |
testStrings[i] = strings.Repeat("#", int(math.Pow(2, float64(i)))) | |
} | |
//fmt.Println(testStrings) | |
t1 := time.Now() | |
for i := range testStrings { | |
_ = splitByWidthMake(testStrings[i], 2) | |
//fmt.Println(t) | |
} | |
elapsed := time.Since(t1) | |
fmt.Println("for loop version elapsed: ", elapsed) | |
t1 = time.Now() | |
for i := range testStrings { | |
_ = splitByWidth(testStrings[i], 2) | |
} | |
elapsed = time.Since(t1) | |
fmt.Println("for loop without make version elapsed: ", elapsed) | |
t1 = time.Now() | |
for i := range testStrings { | |
_ = splitRecursive(testStrings[i], 2) | |
} | |
elapsed = time.Since(t1) | |
fmt.Println("recursive version elapsed: ", elapsed) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
answer the question in stackoverflow: https://stackoverflow.com/questions/25686109/split-string-by-length-in-golang/55833611#55833611