github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/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 "strconv" 18 19 // NthToken returns the Nth token in s, delimited by delim. There is always at least one token: the zeroth token is the 20 // input string if delim doesn't occur in s. The second return value will be false if there is no Nth token. 21 func NthToken(s string, delim rune, n int) (string, bool) { 22 if n < 0 { 23 panic("invalid arguments.") 24 } 25 26 prev := 0 27 curr := 0 28 for ; curr < len(s); curr++ { 29 if s[curr] == uint8(delim) { 30 n-- 31 32 if n >= 0 { 33 prev = curr + 1 34 } else { 35 break 36 } 37 } 38 } 39 40 if n <= 0 && prev <= curr { 41 return s[prev:curr], true 42 } 43 44 return "", false 45 } 46 47 func CommaIfy(n int64) string { 48 str := strconv.FormatInt(n, 10) 49 50 if len(str) < 4 { 51 return str 52 } 53 54 result := "" 55 56 for i := len(str); i >= 0; i -= 3 { 57 if i-4 >= 0 { 58 result = "," + str[i-3:i] + result 59 } else { 60 result = str[0:i] + result 61 } 62 } 63 64 return result 65 }