-2

How found offset index a string in []rune using go?

I can do this work with string type.

if i := strings.Index(input[offset:], "}}"); i > 0 {print(i);}

but i need for runes.

i have a rune and want get offset index.

how can do this work with runes type in go?

example for more undrestand want need:

int offset=0//mean start from 0 (this is important for me)
string text="123456783}}56"
if i := strings.Index(text[offset:], "}}"); i > 0 {print(i);}

output of this example is : 9

but i want do this with []rune type(text variable)

may?

see my current code : https://play.golang.org/p/seImKzVpdh

tank you.

Love Python
  • 25
  • 2
  • 4

1 Answers1

3

Edit #2: You again indicated a new type "meaning" of your question: you want to search a string in a []rune.

Answer: this is not supported directly in the standard library. But it's easy to implement it with 2 for loops:

func search(text []rune, what string) int {
    whatRunes := []rune(what)

    for i := range text {
        found := true
        for j := range whatRunes {
            if text[i+j] != whatRunes[j] {
                found = false
                break
            }
        }
        if found {
            return i
        }
    }
    return -1
}

Testing it:

value := []rune("123}456}}789")
result := search(value, "}}")
fmt.Println(result)

Output (try it on the Go Playground):

7

Edit: You updated the question indicating that you want to search runes in a string.

You may easily convert a []rune to a string using a simple type conversion:

toSearchRunes := []rune{'}', '}'}
toSearch := string(toSearchRunes)

And from there on, you can use strings.Index() as you did in your example:

if i := strings.Index(text[offset:], toSearch); i > 0 {
    print(i)
}

Try it on the Go Playground.

Original answer follows:


string values in Go are stored as UTF-8 encoded bytes. strings.Index() returns you the byte position if the given substring is found.

So basically what you want is to convert this byte-position to rune-position. The unicode/utf8 package contains utility functions for telling the rune-count or rune-length of a string: utf8.RuneCountInString().

So basically you just need to pass the substring to this function:

offset := 0
text := "123456789}}56"
if i := strings.Index(text[offset:], "}}"); i > 0 {
    fmt.Println("byte-pos:", i, "rune-pos:", utf8.RuneCountInString(text[offset:i]))
}

text = "世界}}世界"
if i := strings.Index(text[offset:], "}}"); i > 0 {
    fmt.Println("byte-pos:", i, "rune-pos:", utf8.RuneCountInString(text[offset:i]))
}

Output (try it on the Go Playground):

byte-pos: 9 rune-pos: 9
byte-pos: 6 rune-pos: 2

Note: offset must also be a byte position, because when slicing a string like text[offset:], the index is interpreted as byte-index.

If you want to get the index of a rune, use strings.IndexRune() instead of strings.Index().

icza
  • 389,944
  • 63
  • 907
  • 827