Skip to content

Instantly share code, notes, and snippets.

@guleriagishere
Created May 23, 2020 16:04
Show Gist options
  • Save guleriagishere/8185da56df6d64c2ab652a59808c1011 to your computer and use it in GitHub Desktop.
Save guleriagishere/8185da56df6d64c2ab652a59808c1011 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"bytes"
"fmt"
"strings"
)
//func check(e err) {
// if e != nil {
// log.Panic(e)
// }
//}
// Custom split function. This will split string at 'sbustring' i.e # or // etc....
func SplitAt(substring string) func(data []byte, atEOF bool) (advance int, token []byte, err error) {
searchBytes := []byte(substring)
searchLength := len(substring)
return func(data []byte, atEOF bool) (advance int, token []byte, err error) {
dataLen := len(data)
// Return Nothing if at the end of file or no data passed.
if atEOF && dataLen == 0 {
return 0,nil,nil
}
// Find next separator and return token.
if i := bytes.Index(data, searchBytes); i >= 0 {
return i + searchLength, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return dataLen, data, nil
}
// Request more data.
return 0, nil, nil
}
}
func main() {
const input = "123# \n237 93829938#34823\n56873264"
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(SplitAt("\n"))
// Validate the input
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Printf("Invalid input: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment