0

Why doesn't go have a substring function?

Can i do something like prototyping from javascript so i can at least do something like:

string.substring(0,7) 

or am i forced to use my function here?:

func substring(str string, start int, length int) string {
    return string([]rune(str)[start:length+start])
}
3
  • 2
    Why function? If you have byte offsets, str[from:to], if you have rune offsets, string([]rune(str)[from:to]) Apr 21, 2020 at 20:55
  • 1
    Work with byte offsets so that you can use string slice operations. Programs that work with rune indexes convert to []rune, do some work on the runes and convert back to the string when done. Apr 21, 2020 at 20:55
  • 1
    Because it doesn't need one. string.Substring(str, 0,7) is a lot longer than str[:7] Apr 21, 2020 at 20:59

1 Answer 1

8

Substrings is a "thing" in Go too: slicing a string results in a string which shares memory with the original string.

The difference is that in Go the indices are byte-indices, not character or rune indices. Go stores the UTF-8 encoded byte sequence of texts in a string.

If your input consists of ASCII characters only (byte values less than 128), then using byte indices is the same as using rune indices:

s := "abcdef"
fmt.Println(s[1:3])

This will output:

bc

If your input may contain multi-byte unicode characters, then you have to decode the (UTF-8) bytes of the string. For that, there is the standard unicode/utf8 package, or you may use for range over the string which does the same thing.

The for range over the string decodes the bytes, and each iteration "yields" one rune of the string, and also returns the starting byte position of the rune.

This is how we can use that to construct a substr() function:

func substr(s string, start, end int) string {
    counter, startIdx := 0, 0
    for i := range s {
        if counter == start {
            startIdx = i
        }
        if counter == end {
            return s[startIdx:i]
        }
        counter++
    }
    return s[startIdx:]
}

substr() takes a string and a start (inclusive) and end (exclusive) rune indices, and returns a substring according to that. Checks (like start <= end) are omitted for brevity.

Testing it:

s := "abcdef"
fmt.Println(substr(s, 1, 3))

s = "世界世界世界"
fmt.Println(substr(s, 1, 3))
fmt.Println(substr(s, 1, 100))

Output (try it on the Go Playground):

bc
界世
界世界世界
4
  • Wouldn't this be faster?:func substring(str string, start int, length int) string { return string([]rune(str)[start:length+start]) } Apr 21, 2020 at 22:13
  • @KilianHertel Definitely not, because that copies the string content when converting to rune slice, and then slices it, and converts it back to string making another copy. My solution does not make any copies, the returned string is truly a substring of the input. Also, converting a string to []rune has to decode all runes, while my solution only decodes what is necessary. Benchmark it if you want proof.
    – icza
    Apr 21, 2020 at 22:16
  • But s[1:3] would be the way to go then its 5 tines faster then substr. And substr is faster than substring pretty heavy impact though. Apr 21, 2020 at 22:38
  • @KilianHertel As noted in the answer, simple slicing like s[1:3] is OK if the string only contains ASCII characters. But it does not work with the second example ("世界世界世界"), for that you need the presented substr() function. Note that substr() works with ASCII strings too.
    – icza
    Apr 22, 2020 at 5:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.