-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.go
More file actions
60 lines (55 loc) · 1.62 KB
/
strings.go
File metadata and controls
60 lines (55 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) 2023–2024 The convert developers. All rights reserved.
// Project site: https://github.com/gotmc/convert
// Use of this source code is governed by a MIT-style license that
// can be found in the LICENSE.txt file for the project.
package convert
import (
"fmt"
"strconv"
"strings"
)
// StripDoubleQuotes will strip double quotes at the beginning and end of a
// string.
func StripDoubleQuotes(s string) string {
s = strings.TrimSpace(s)
s = strings.TrimPrefix(s, "\"")
return strings.TrimSuffix(s, "\"")
}
// StringToNFloats uses the given separator to split a string into the
// expected number of floats.
func StringToNFloats(s, sep string, numExpected int) ([]float64, error) {
slice := strings.Split(s, sep)
if len(slice) != numExpected {
return nil, fmt.Errorf(
"error: didn't split into number expected given string: %s", s,
)
}
nums := make([]float64, numExpected)
for i, s := range slice {
num, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
if err != nil {
return nil, fmt.Errorf("error converting %s to float64", s)
}
nums[i] = num
}
return nums, nil
}
// StringToFloats uses the given separator to split a string into an unknown
// number of floats.
func StringToFloats(s, sep string) ([]float64, error) {
slice := strings.Split(s, sep)
if len(slice) < 1 {
return nil, fmt.Errorf(
"error splitting the given string: %s", s,
)
}
nums := make([]float64, len(slice))
for i, s := range slice {
num, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
if err != nil {
return nil, fmt.Errorf("error converting %s to float64", s)
}
nums[i] = num
}
return nums, nil
}