Logo

Programming-Idioms

  • Elixir
  • Go

Idiom #46 Extract beginning of string (prefix)

Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.

i := 0
count := 0
for i = range s {
	if count >= 5 {
		break
	}
	count++
}
t := s
if count >= 5 {
	t = s[:i]
}

This does not allocate
t := s
r := []rune(s)
if len(r) > 5 {
	t = string(r[:5])
}

This incurs a run-time cost proportional to len(s).
t = String.slice(s, 0, 5)
T : String := S (1 .. 5);

New implementation...