Skip to content

Instantly share code, notes, and snippets.

@KEINOS
Last active December 13, 2023 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KEINOS/141baa7736c2d922f18eaada299135b5 to your computer and use it in GitHub Desktop.
Save KEINOS/141baa7736c2d922f18eaada299135b5 to your computer and use it in GitHub Desktop.
[golang] "io.reader" read by characters

How to read by characters using io.Reader in Go

The below golang code will print the input rune by rune.

package main

import (
	"bufio"
	"fmt"
	"strings"
)

// This method is no-good for emojis.
// Also note the differences between the first and the second ペンギン.
// We should consider using: https://github.com/rivo/uniseg
func Example() {
	input := `abcdefg1234567890あいうえお💩👍🏼!ペンギンペンギンペンギン`
	inputReader := strings.NewReader(input)

	scanner := bufio.NewScanner(inputReader)
	scanner.Split(bufio.ScanRunes)

	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
	// Output:
	// a
	// b
	// c
	// d
	// e
	// f
	// g
	// 1
	// 2
	// 3
	// 4
	// 5
	// 6
	// 7
	// 8
	// 9
	// 0
	// あ
	// い
	// う
	// え
	// お
	// 💩
	// 👍
	// 🏼
	// !
	// ヘ
	// ゚
	// ン
	// キ
	// ゙
	// ン
	// ヘ
	// ゚
	// ン
	// キ
	// ゙
	// ン
	// ペ
	// ン
	// ギ
	// ン
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment