Return first n chars of a string
10,216
Solution 1
Your code is fine unless you want to work with unicode:
fmt.Println(firstN("世界 Hello", 1)) // �
To make it work with unicode you can modify the function in the following way:
// allocation free version
func firstN(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
fmt.Println(firstN("世界 Hello", 1)) // 世
// you can also convert a string to a slice of runes, but it will require additional memory allocations
func firstN2(s string, n int) string {
r := []rune(s)
if len(r) > n {
return string(r[:n])
}
return s
}
fmt.Println(firstN2("世界 Hello", 1)) // 世
Solution 2
college := "ARMY INSTITUTE OF TECHNOLOGY PUNE"
fmt.Println(college)
name := college[0:4]
fmt.Println(name)
Related videos on Youtube
Author by
ryan
Updated on June 04, 2022Comments
-
ryan over 1 year
What is the best way to return first n chars as substring of a string, when there isn't n chars in the string, just return the string itself.
I can do the following:
func firstN(s string, n int) string { if len(s) > n { return s[:n] } return s }
but is there a cleaner way?
BTW, in Scala, I can just do
s take n
.-
JimB almost 7 yearsNo, Go is not Scala. How is
s take n
"cleaner" thanfirstN(s, n)
? -
Cerise Limón almost 7 yearsWhen you say char, do you mean byte or rune? The code in the question looks good to me if the goal is to return the first N bytes. A loop is required to return the first N runes.
-
-
Maria Efimenko over 2 yearsI wouldn't do that if I were you) if college consisted of 2 symbols, your code would panic.
-
Sumer over 2 yearsAgree @MariaEfimenko , better to put checks comparing length of string and max bound