github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/strhelp/string_help.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package strhelp 16 17 import ( 18 "fmt" 19 "strconv" 20 "strings" 21 ) 22 23 // NthToken returns the Nth token in s, delimited by delim. There is always at least one token: the zeroth token is the 24 // input string if delim doesn't occur in s. The second return value will be false if there is no Nth token. 25 func NthToken(s string, delim rune, n int) (string, bool) { 26 if n < 0 { 27 panic("invalid arguments.") 28 } 29 30 prev := 0 31 curr := 0 32 for ; curr < len(s); curr++ { 33 if s[curr] == uint8(delim) { 34 n-- 35 36 if n >= 0 { 37 prev = curr + 1 38 } else { 39 break 40 } 41 } 42 } 43 44 if n <= 0 && prev <= curr { 45 return s[prev:curr], true 46 } 47 48 return "", false 49 } 50 51 func CommaIfy(n int64) string { 52 str := strconv.FormatInt(n, 10) 53 54 if len(str) < 4 { 55 return str 56 } 57 58 result := "" 59 60 for i := len(str); i >= 0; i -= 3 { 61 if i-4 >= 0 { 62 result = "," + str[i-3:i] + result 63 } else { 64 result = str[0:i] + result 65 } 66 } 67 68 return result 69 } 70 71 // LineStrBuilder is a utility class for building strings line by line 72 type LineStrBuilder []string 73 74 // AppendLine works like append in that it returns an instance of a LineStrBuilder with the contents updated to contain 75 // the additional line. lsb = lsb.AppendLine("n: %d, s: %s", n, s) 76 func (lsb LineStrBuilder) AppendLine(strFmt string, args ...interface{}) LineStrBuilder { 77 updated := append(lsb, fmt.Sprintf(strFmt, args...)) 78 return updated 79 } 80 81 // String returns the built string with all lines separated by newlines 82 func (lsb LineStrBuilder) String() string { 83 s := strings.Join(lsb, "\n") 84 return s 85 }