substring #golang

I didn’t think up how to take substring from string data, so I looked up how to do it.

I found the solution in go-nuts group(very helpful resource).


func substr(s string,pos,length int) string{
l := pos+length
if l > len(bytes) {
l = len(bytes)
return string(bytes[pos:l])

the original source use not byte but int. but it didn’t work.
so I modified int into byte. It seems to be working well.

I uses it as utility function.


2 thoughts on “substring #golang”

  1. The conversion to []byte is unnecessary.
    You can just do, s[pos:pos+length] directly on the string.

    This will give you a substring of the bytes of the string, but not the characters.
    The conversion to []rune and the slicing of that will give you a substring of unicode code points, which is more likely what you want.

  2. Thank you for your comment.

    when slicing multibyte letters, I found conversion to []byte is not working, and conversion to []rune works good. Around me, multibyte letters are often used "日本"(japan), "東京"(tokyo). I could figure out what you wrote.

    Nice suggestion.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.