C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Loop: We can loop over the characters in a string by accessing its length. We use all indexes from 0 to the len minus one (inclusive).
Golang program that uses len to get string length
package main
import "fmt"
func main() {
value := "cat"
// Take length of string with len.
length := len(value)
fmt.Println(length)
// Loop over the string with len.
for i := 0; i < len(value); i++ {
fmt.Println(string(value[i]))
}
}
Output
3
c
a
t
Append: We call the append() built-in to add a fifth element to the slice. The len() method then returns 5.
Quote: The length of a slice "s" can be discovered by the built-in function len; unlike with arrays it may change during execution.
Specification: golang.orgTip: The specification notes that lengths of slices are discovered with len. A stored length value is returned.
Golang program that uses len, append on slice
package main
import "fmt"
func main() {
slice := []int{10, 20, 30, 40}
// Get length of slice with len.
length := len(slice)
fmt.Println(slice)
fmt.Println(length)
// Append an element, and take the length again.
slice = append(slice, 50)
fmt.Println(slice)
fmt.Println(len(slice))
}
Output
[10 20 30 40]
4
[10 20 30 40 50]
5
Golang program that uses len on nil slice
package main
import "fmt"
func main() {
// A slice with len of 3.
value := []int{10, 20, 30}
fmt.Println(len(value))
// A nil slice has a len of 0.
value = nil
fmt.Println(len(value))
}
Output
3
0
So: Len is fast. On my system it can be used 10 million times on a string of any length in less than 10 ms.
Version 1: This version of the code uses the len built-in on a short string of just 3 characters.
StringsVersion 2: This version uses len on a longer string of 65 characters. It shows that len returns in constant time.
Golang program that times string len
package main
import (
"fmt"
"time"
)
func main() {
// Length is 3.
string1 := "cat"
// Length is 13 times 5 which is 65.
string2 := "cat0123456789" +
"cat0123456789" +
"cat0123456789" +
"cat0123456789" +
"cat0123456789"
t0 := time.Now()
// Version 1: length of short string.
for i := 0; i < 10000000; i++ {
result := len(string1)
if result != 3 {
return
}
}
t1 := time.Now()
// Version 2: length of long string.
for i := 0; i < 10000000; i++ {
result := len(string2)
if result != 65 {
return
}
}
t2 := time.Now()
// Print results.
fmt.Println(t1.Sub(t0))
fmt.Println(t2.Sub(t1))
}
Output
7.0049ms len( 3 character string)
7.0189ms len(65 character string)