You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
// Package parse provides utility functions for parsing and reading data from files.
|
|
package parse
|
|
|
|
import (
|
|
"bufio"
|
|
"log"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"golang.org/x/exp/constraints"
|
|
)
|
|
|
|
// ReadLines reads all lines from a file specified by fileName and returns them as a slice of strings.
|
|
func ReadLines(fileName string) []string {
|
|
result := []string{}
|
|
file, err := os.Open(fileName)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
result = append(result, scanner.Text())
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// ParseIntArray parses a string containing integer values separated by a specified separator and returns a slice of integers.
|
|
func ParseIntArray[T constraints.Integer](s string, sep string) []T {
|
|
result := []T{}
|
|
|
|
var vals []string
|
|
if sep == " " {
|
|
vals = strings.Fields(strings.TrimSpace(s))
|
|
} else {
|
|
vals = strings.Split(strings.TrimSpace(s), sep)
|
|
}
|
|
|
|
for _, val := range vals {
|
|
n, e := strconv.ParseInt(strings.TrimSpace(val), 10, 64)
|
|
if e != nil {
|
|
log.Fatal(e)
|
|
}
|
|
|
|
result = append(result, T(n))
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// SplitNoBlank splits a string by a specified separator and returns a slice of the non-empty parts.
|
|
func SplitNoBlank(s string, sep string) []string {
|
|
splitted_line := strings.Split(s, sep)
|
|
|
|
result := []string{}
|
|
|
|
for _, part := range splitted_line {
|
|
if part != "" {
|
|
result = append(result, part)
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|