Skip to content

Instantly share code, notes, and snippets.

@karl-zylinski
Last active October 1, 2024 20:41
Show Gist options
  • Save karl-zylinski/7b3207f29d46e2ef2eac7618f15e1a89 to your computer and use it in GitHub Desktop.
Save karl-zylinski/7b3207f29d46e2ef2eac7618f15e1a89 to your computer and use it in GitHub Desktop.
Example of how to look at next rune when iterating a string
package runefun
import fmt "core:fmt"
import "core:unicode/utf8"
main :: proc() {
str := "小猫咪"
// i is the byte index
for r, i in str {
// byte index of next rune
next_idx := i+utf8.rune_size(r)
if next_idx < len(str) {
// rune_at expects byte index
next_rune := utf8.rune_at(str, next_idx)
fmt.println(next_rune)
}
}
}
// This program will print
// 猫
// 咪
// I.e. it looks ahead at next rune at each lap of the loop.
// Note: There is also utf8.rune_at_pos(str, rune_idx) that takes a rune index.
// But internally it does a loop over the string to find the rune with that index,
// it is better to just use the rune_at with a byte index, it does no looping.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment