gstr
provides powerful and convenient text processing components, with a large number of commonly used string processing methods built in, making it more comprehensive and rich compared to the Golang
standard library, suitable for dealing with most business scenarios.
Usage:
import "github.com/gogf/gf/v2/text/gstr"
API Documentation:
https://pkg.go.dev/github.com/gogf/gf/v2/text/gstr
The list of common methods below might be outdated compared to code updates with new features. For more methods and examples, please refer to the code documentation: https://pkg.go.dev/github.com/gogf/gf/v2/text/gstr
String Judgment
IsNumeric
-
Description:
IsNumeric
verifies whether the strings
is a number. -
Format:
IsNumeric(s string) bool
- Example:
func ExampleIsNumeric() {
fmt.Println(gstr.IsNumeric("88"))
fmt.Println(gstr.IsNumeric("3.1415926"))
fmt.Println(gstr.IsNumeric("abc"))
// Output:
// true
// true
// false
}
String Length
LenRune
-
Description:
LenRune
returns the length of aunicode
string. -
Format:
LenRune(str string) int
- Example:
func ExampleLenRune() {
var (
str = `GoFrame框架`
result = gstr.LenRune(str)
)
fmt.Println(result)
// Output:
// 9
}
String Creation
Repeat
-
Description:
Repeat
returns a new string consisting of theinput
string repeatedmultiplier
times. -
Format:
Repeat(input string, multiplier int) string
- Example:
func ExampleRepeat() {
var (
input = `goframe `
multiplier = 3
result = gstr.Repeat(input, multiplier)
)
fmt.Println(result)
// Output:
// goframe goframe goframe
}
Case Conversion
ToLower
-
Description:
ToLower
converts allUnicode
characters ins
to lowercase and returns its copy. -
Format:
ToLower(s string) string
- Example:
func ExampleToLower() {
var (
s = `GOFRAME`
result = gstr.ToLower(s)
)
fmt.Println(result)
// Output:
// goframe
}
ToUpper
-
Description:
ToUpper
converts allUnicode
characters ins
to uppercase and returns its copy. -
Format:
ToUpper(s string) string
- Example:
func ExampleToUpper() {
var (
s = `goframe`
result = gstr.ToUpper(s)
)
fmt.Println(result)
// Output:
// GOFRAME
}
UcFirst
-
Description:
UcFirst
capitalizes the first character ofs
and returns its copy. -
Format:
UcFirst(s string) string
- Example:
func ExampleUcFirst() {
var (
s = `hello`
result = gstr.UcFirst(s)
)
fmt.Println(result)
// Output:
// Hello
}
LcFirst
-
Description:
LcFirst
converts the first character ofs
to lowercase and returns its copy. -
Format:
LcFirst(s string) string
- Example:
func ExampleLcFirst() {
var (
str = `Goframe`
result = gstr.LcFirst(str)
)
fmt.Println(result)
// Output:
// goframe
}
UcWords
-
Description:
UcWords
capitalizes the first character of each word in the stringstr
. -
Format:
UcWords(str string) string
- Example:
func ExampleUcWords() {
var (
str = `hello world`
result = gstr.UcWords(str)
)
fmt.Println(result)
// Output:
// Hello World
}
IsLetterLower
-
Description:
IsLetterLower
verifies whether the given characterb
is lowercase. -
Format:
IsLetterLower(b byte) bool
- Example:
func ExampleIsLetterLower() {
fmt.Println(gstr.IsLetterLower('a'))
fmt.Println(gstr.IsLetterLower('A'))
// Output:
// true
// false
}
IsLetterUpper
-
Description:
IsLetterUpper
verifies whether the characterb
is uppercase. -
Format:
IsLetterUpper(b byte) bool
- Example:
func ExampleIsLetterUpper() {
fmt.Println(gstr.IsLetterUpper('A'))
fmt.Println(gstr.IsLetterUpper('a'))
// Output:
// true
// false
}
String Comparison
Compare
-
Description:
Compare
returns an integer comparing two strings lexicographically. Ifa == b
, it returns0
; ifa < b
, it returns-1
; ifa > b
, it returns+1
. -
Format:
Compare(a, b string) int
- Example:
func ExampleCompare() {
fmt.Println(gstr.Compare("c", "c"))
fmt.Println(gstr.Compare("a", "b"))
fmt.Println(gstr.Compare("c", "b"))
// Output:
// 0
// -1
// 1
}
Equal
-
Description:
Equal
returns whethera
andb
are equal, case-insensitively. -
Format:
Equal(a, b string) bool
- Example:
func ExampleEqual() {
fmt.Println(gstr.Equal(`A`, `a`))
fmt.Println(gstr.Equal(`A`, `A`))
fmt.Println(gstr.Equal(`A`, `B`))
// Output:
// true
// true
// false
}
Split and Join
Split
-
Description:
Split
splitsstr
into[]string
usingdelimiter
. -
Format:
Split(str, delimiter string) []string
- Example:
func ExampleSplit() {
var (
str = `a|b|c|d`
delimiter = `|`
result = gstr.Split(str, delimiter)
)
fmt.Printf(`%#v`, result)
// Output:
// []string{"a", "b", "c", "d"}
}
SplitAndTrim
-
Description:
SplitAndTrim
splitsstr
into[]string
usingdelimiter
and callsTrim
on each element of[]string
, ignoring elements that are empty afterTrim
. -
Format:
SplitAndTrim(str, delimiter string, characterMask ...string) []string
- Example:
func ExampleSplitAndTrim() {
var (
str = `a|b|||||c|d`
delimiter = `|`
result = gstr.SplitAndTrim(str, delimiter)
)
fmt.Printf(`%#v`, result)
// Output:
// []string{"a", "b", "c", "d"}
}
Join
-
Description:
Join
concatenates each element ofarray
into a new string. The parametersep
is used as the separator for the new string. -
Format:
Join(array []string, sep string) string
- Example:
func ExampleJoin() {
var (
array = []string{"goframe", "is", "very", "easy", "to", "use"}
sep = ` `
result = gstr.Join(array, sep)
)
fmt.Println(result)
// Output:
// goframe is very easy to use
}
JoinAny
-
Description:
JoinAny
concatenates each element ofarray
into a new string. The parametersep
is used as the separator for the new string. The parameterarray
can be of any type. -
Format:
JoinAny(array interface{}, sep string) string
- Example:
func ExampleJoinAny() {
var (
sep = `,`
arr2 = []int{99, 73, 85, 66}
result = gstr.JoinAny(arr2, sep)
)
fmt.Println(result)
// Output:
// 99,73,85,66
}
Explode
-
Description:
Explode
splitsstr
into[]string
using the delimiterdelimiter
. -
Format:
Explode(delimiter, str string) []string
- Example:
func ExampleExplode() {
var (
str = `Hello World`
delimiter = " "
result = gstr.Explode(delimiter, str)
)
fmt.Printf(`%#v`, result)
// Output:
// []string{"Hello", "World"}
}
Implode
-
Description:
Implode
joins each element of thepieces
string array usingglue
. -
Format:
Implode(glue string, pieces []string) string
- Example:
func ExampleImplode() {
var (
pieces = []string{"goframe", "is", "very", "easy", "to", "use"}
glue = " "
result = gstr.Implode(glue, pieces)
)
fmt.Println(result)
// Output:
// goframe is very easy to use
}
ChunkSplit
-
Description:
ChunkSplit
splits the string into smaller chunks ofchunkLen
and joins each chunk withend
. -
Format:
ChunkSplit(body string, chunkLen int, end string) string
- Example:
func ExampleChunkSplit() {
var (
body = `1234567890`
chunkLen = 2
end = "#"
result = gstr.ChunkSplit(body, chunkLen, end)
)
fmt.Println(result)
// Output:
// 12#34#56#78#90#
}
Fields
-
Description:
Fields
returns[]string
representing each word in the string. -
Format:
Fields(str string) []string
- Example:
func ExampleFields() {
var (
str = `Hello World`
result = gstr.Fields(str)
)
fmt.Printf(`%#v`, result)
// Output:
// []string{"Hello", "World"}
}
Escape Processing
AddSlashes
-
Description:
AddSlashes
adds an escape character'\'
before the symbols in the string. -
Format:
AddSlashes(str string) string
- Example:
func ExampleAddSlashes() {
var (
str = `'aa'"bb"cc\r\n\d\t`
result = gstr.AddSlashes(str)
)
fmt.Println(result)
// Output:
// \'aa\'\"bb\"cc\\r\\n\\d\\t
}
StripSlashes
-
Description:
StripSlashes
removes the escape characters'\'
from stringstr
. -
Format:
StripSlashes(str string) string
- Example:
func ExampleStripSlashes() {
var (
str = `C:\\windows\\GoFrame\\test`
result = gstr.StripSlashes(str)
)
fmt.Println(result)
// Output:
// C:\windows\GoFrame\test
}
QuoteMeta
-
Description:
QuoteMeta
adds an escape character'\'
before each character instr
among '\ + * ? [ ^ ] ( $ )
. -
Format:
QuoteMeta(str string, chars ...string) string
- Example:
func ExampleQuoteMeta() {
{
var (
str = `.\+?[^]()`
result = gstr.QuoteMeta(str)
)
fmt.Println(result)
}
{
var (
str = `https://goframe.org/pages/viewpage.action?pageId=1114327`
result = gstr.QuoteMeta(str)
)
fmt.Println(result)
}
// Output:
// \.\\\+\?\[\^\]\(\)
// https://goframe\.org/pages/viewpage\.action\?pageId=1114327
}
Count Statistics
Count
-
Description:
Count
calculates the number of timessubstr
occurs ins
. Ifsubstr
is not found ins
, it returns0
. -
Format:
Count(s, substr string) int
- Example:
func ExampleCount() {
var (
str = `goframe is very, very easy to use`
substr1 = "goframe"
substr2 = "very"
result1 = gstr.Count(str, substr1)
result2 = gstr.Count(str, substr2)
)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 1
// 2
}
CountI
-
Description:
Count
calculates the number of timessubstr
occurs ins
, case-insensitively. If not found, returns0
. -
Format:
CountI(s, substr string) int
- Example:
func ExampleCountI() {
var (
str = `goframe is very, very easy to use`
substr1 = "GOFRAME"
substr2 = "VERY"
result1 = gstr.CountI(str, substr1)
result2 = gstr.CountI(str, substr2)
)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 1
// 2
}
CountWords
-
Description:
CountWords
returns amap[string]int
with statistics of words used instr
. -
Format:
CountWords(str string) map[string]int
- Example:
func ExampleCountWords() {
var (
str = `goframe is very, very easy to use!`
result = gstr.CountWords(str)
)
fmt.Printf(`%#v`, result)
// Output:
// map[string]int{"easy":1, "goframe":1, "is":1, "to":1, "use!":1, "very":1, "very,":1}
}
CountChars
-
Description:
CountChars
returns statistics of characters used instr
asmap[string]int
. ThenoSpace
parameter controls whether to count spaces. -
Format:
CountChars(str string, noSpace ...bool) map[string]int
- Example:
func ExampleCountChars() {
var (
str = `goframe`
result = gstr.CountChars(str)
)
fmt.Println(result)
// May Output:
// map[a:1 e:1 f:1 g:1 m:1 o:1 r:1]
}
Array Processing
SearchArray
-
Description:
SearchArray
searches string's'
in[]string 'a'
case-sensitively and returns its index in'a'
. If's'
is not found, it returns-1
. -
Format:
SearchArray(a []string, s string) int
- Example:
func ExampleSearchArray() {
var (
array = []string{"goframe", "is", "very", "nice"}
str = `goframe`
result = gstr.SearchArray(array, str)
)
fmt.Println(result)
// Output:
// 0
}
InArray
-
Description:
InArray
verifies whether the[]string 'a'
contains the string' s '
. -
Format:
InArray(a []string, s string) bool
- Example:
func ExampleInArray() {
var (
a = []string{"goframe", "is", "very", "easy", "to", "use"}
s = "goframe"
result = gstr.InArray(a, s)
)
fmt.Println(result)
// Output:
// true
}
PrefixArray
-
Description:
PrefixArray
adds the prefix'prefix'
to each string in[]string array
. -
Format:
PrefixArray(array []string, prefix string)
- Example:
func ExamplePrefixArray() {
var (
strArray = []string{"tom", "lily", "john"}
)
gstr.PrefixArray(strArray, "classA_")
fmt.Println(strArray)
// Output:
// [classA_tom classA_lily classA_john]
}
Naming Conversion
CaseCamel
-
Description:
CaseCamel
converts a string to a camel case format (capitalize the first letter). -
Format:
CaseCamel(s string) string
- Example:
func ExampleCaseCamel() {
var (
str = `hello world`
result = gstr.CaseCamel(str)
)
fmt.Println(result)
// Output:
// HelloWorld
}
CaseCamelLower
-
Description:
CaseCamelLower
converts a string to camel case format (lowercase the first letter). -
Format:
CaseCamelLower(s string) string
- Example:
func ExampleCaseCamelLower() {
var (
str = `hello world`
result = gstr.CaseCamelLower(str)
)
fmt.Println(result)
// Output:
// helloWorld
}
CaseSnake
-
Description:
CaseSnake
replaces symbols (underscore, space, dot, hyphen) in a string with underscores (_
) and converts all to lowercase. -
Format:
CaseSnake(s string) string
- Example:
func ExampleCaseSnake() {
var (
str = `hello world`
result = gstr.CaseSnake(str)
)
fmt.Println(result)
// Output:
// hello_world
}
CaseSnakeScreaming
-
Description:
CaseSnakeScreaming
replaces symbols (underscore, space, dot, hyphen) in a string with underscores ('_'
) and converts all letters to uppercase. -
Format:
CaseSnakeScreaming(s string) string
- Example:
func ExampleCaseSnakeScreaming() {
var (
str = `hello world`
result = gstr.CaseSnakeScreaming(str)
)
fmt.Println(result)
// Output:
// HELLO_WORLD
}
CaseSnakeFirstUpper
-
Description:
CaseSnakeFirstUpper
converts uppercase letters to lowercase and adds an underscore'_'
before them, except the first uppercase letter, which is only converted to lowercase without an underscore. -
Format:
CaseSnakeFirstUpper(word string, underscore ...string) string
- Example:
func ExampleCaseSnakeFirstUpper() {
var (
str = `RGBCodeMd5`
result = gstr.CaseSnakeFirstUpper(str)
)
fmt.Println(result)
// Output:
// rgb_code_md5
}
CaseKebab
-
Description:
CaseKebab
replaces symbols (underscore, space, dot,) in a string with hyphens ('-'
) and converts all to lowercase. -
Format:
CaseKebab(s string) string
- Example:
func ExampleCaseKebab() {
var (
str = `hello world`
result = gstr.CaseKebab(str)
)
fmt.Println(result)
// Output:
// hello-world
}
CaseKebabScreaming
-
Description:
CaseKebabScreaming
replaces symbols (underscore, space, dot, hyphen) in a string with hyphens ('-'
) and converts all to uppercase. -
Format:
CaseKebabScreaming(s string) string
- Example:
func ExampleCaseKebabScreaming() {
var (
str = `hello world`
result = gstr.CaseKebabScreaming(str)
)
fmt.Println(result)
// Output:
// HELLO-WORLD
}
CaseDelimited
-
Description:
CaseDelimited
replaces symbols in a string based on specified delimiters. -
Format:
CaseDelimited(s string, del byte) string
- Example:
func ExampleCaseDelimited() {
var (
str = `hello world`
del = byte('-')
result = gstr.CaseDelimited(str, del)
)
fmt.Println(result)
// Output:
// hello-world
}
CaseDelimitedScreaming
-
Description:
CaseDelimitedScreaming
replaces symbols (space, underscore, dot, hyphen) in a string with the second parameter delimiter, converting to uppercase if the third parameter istrue
, or to lowercase iffalse
. -
Format:
CaseDelimitedScreaming(s string, del uint8, screaming bool) string
- Example:
func ExampleCaseDelimitedScreaming() {
{
var (
str = `hello world`
del = byte('-')
result = gstr.CaseDelimitedScreaming(str, del, true)
)
fmt.Println(result)
}
{
var (
str = `hello world`
del = byte('-')
result = gstr.CaseDelimitedScreaming(str, del, false)
)
fmt.Println(result)
}
// Output:
// HELLO-WORLD
// hello-world
}
Contains Check
Contains
-
Description:
Contains
returns whether the stringstr
contains the substringsubstr
, case-sensitively. -
Format:
Contains(str, substr string) bool
- Example:
func ExampleContains() {
{
var (
str = `Hello World`
substr = `Hello`
result = gstr.Contains(str, substr)
)
fmt.Println(result)
}
{
var (
str = `Hello World`
substr = `hello`
result = gstr.Contains(str, substr)
)
fmt.Println(result)
}
// Output:
// true
// false
}
ContainsI
-
Description:
ContainsI
verifies whethersubstr
is instr
, case-insensitively. -
Format:
ContainsI(str, substr string) bool
- Example:
func ExampleContainsI() {
var (
str = `Hello World`
substr = "hello"
result1 = gstr.Contains(str, substr)
result2 = gstr.ContainsI(str, substr)
)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// false
// true
}
ContainsAny
-
Description:
ContainsAny
verifies whethers
containschars
. -
Format:
ContainsAny(s, chars string) bool
- Example:
func ExampleContainsAny() {
{
var (
s = `goframe`
chars = "g"
result = gstr.ContainsAny(s, chars)
)
fmt.Println(result)
}
{
var (
s = `goframe`
chars = "G"
result = gstr.ContainsAny(s, chars)
)
fmt.Println(result)
}
// Output:
// true
// false
}
String Conversion
Chr
-
Description:
Chr
returns theascii
character string for a number0-255
. -
Format:
Chr(ascii int) string
- Example:
func ExampleChr() {
var (
ascii = 65 // A
result = gstr.Chr(ascii)
)
fmt.Println(result)
// Output:
// A
}
Ord
-
Description:
Ord
converts the first byte of a string to a value between0-255
. -
Format:
Ord(char string) int
- Example:
func ExampleOrd() {
var (
str = `goframe`
result = gstr.Ord(str)
)
fmt.Println(result)
// Output:
// 103
}
OctStr
-
Description:
OctStr
converts an octal string instr
to its original string form. -
Format:
OctStr(str string) string
- Example:
func ExampleOctStr() {
var (
str = `\346\200\241`
result = gstr.OctStr(str)
)
fmt.Println(result)
// Output:
// 怡
}
Reverse
-
Description:
Reverse
returns the reversed string ofstr
. -
Format:
Reverse(str string) string
- Example:
func ExampleReverse() {
var (
str = `123456`
result = gstr.Reverse(str)
)
fmt.Println(result)
// Output:
// 654321
}
NumberFormat
-
Description:
NumberFormat
formats a number with thousand separators.- Parameter
decimal
sets the number of decimal points. - Parameter
decPoint
sets the decimal point separator. - Parameter
thousand
sets the thousand separator.
- Parameter
-
Format:
NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string
- Example:
func ExampleNumberFormat() {
var (
number float64 = 123456
decimals = 2
decPoint = "."
thousandsSep = ","
result = gstr.NumberFormat(number, decimals, decPoint, thousandsSep)
)
fmt.Println(result)
// Output:
// 123,456.00
}
Shuffle
-
Description:
Shuffle
returns a randomly shuffled version ofstr
. -
Format:
Shuffle(str string) string
- Example:
func ExampleShuffle() {
var (
str = `123456`
result = gstr.Shuffle(str)
)
fmt.Println(result)
// May Output:
// 563214
}
HideStr
-
Description:
HideStr
converts a percentagepercent
of characters instr
, starting from the middle, to thehide
string. -
Format:
HideStr(str string, percent int, hide string) string
- Example:
func ExampleHideStr() {
var (
str = `13800138000`
percent = 40
hide = `*`
result = gstr.HideStr(str, percent, hide)
)
fmt.Println(result)
// Output:
// 138****8000
}
Nl2Br
-
Description:
Nl2Br
inserts HTML line break(' br ' |<br />)
before all newline characters in a string: \n\r, \r\n, \r, \n. -
Format:
Nl2Br(str string, isXhtml ...bool) string
- Example:
func ExampleNl2Br() {
var (
str = `goframe
is
very
easy
to
use`
result = gstr.Nl2Br(str)
)
fmt.Println(result)
// Output:
// goframe<br>is<br>very<br>easy<br>to<br>use
}
WordWrap
-
Description:
WordWrap
uses line breaks to wrapstr
to a given number of characters (without splitting words). -
Format:
WordWrap(str string, width int, br string) string
- Example:
func ExampleWordWrap() {
{
var (
str = `A very long woooooooooooooooooord. and something`
width = 8
br = "\n"
result = gstr.WordWrap(str, width, br)
)
fmt.Println(result)
}
{
var (
str = `The quick brown fox jumped over the lazy dog.`
width = 20
br = "<br />\n"
result = gstr.WordWrap(str, width, br)
)
fmt.Printf("%v", result)
}
// Output:
// A very
// long
// woooooooooooooooooord.
// and
// something
// The quick brown fox<br />
// jumped over the lazy<br />
// dog.
}
Domain Processing
IsSubDomain
-
Description:
IsSubDomain
verifies whethersubDomain
is a subdomain ofmainDomain
. Supports'*'
inmainDomain
. -
Format:
IsSubDomain(subDomain string, mainDomain string) bool
- Example:
func ExampleIsSubDomain() {
var (
subDomain = `s.goframe.org`
mainDomain = `goframe.org`
result = gstr.IsSubDomain(subDomain, mainDomain)
)
fmt.Println(result)
// Output:
// true
}
Parameter Parsing
Parse
-
Description:
Parse
parses a string and returns it asmap[string]interface{}
. -
Format:
Parse(s string) (result map[string]interface{}, err error)
- Example:
func ExampleParse() {
{
var (
str = `v1=m&v2=n`
result, _ = gstr.Parse(str)
)
fmt.Println(result)
}
{
var (
str = `v[a][a]=m&v[a][b]=n`
result, _ = gstr.Parse(str)
)
fmt.Println(result)
}
{
// The form of nested Slice is not yet supported.
var str = `v[][]=m&v[][]=n`
result, err := gstr.Parse(str)
if err != nil {
panic(err)
}
fmt.Println(result)
}
{
// This will produce an error.
var str = `v=m&v[a]=n`
result, err := gstr.Parse(str)
if err != nil {
println(err)
}
fmt.Println(result)
}
{
var (
str = `a .[[b=c`
result, _ = gstr.Parse(str)
)
fmt.Println(result)
}
// May Output:
// map[v1:m v2:n]
// map[v:map[a:map[a:m b:n]]]
// map[v:map[]]
// Error: expected type 'map[string]interface{}' for key 'v', but got 'string'
// map[]
// map[a___[b:c]
}
Position Finding
Pos
-
Description:
Pos
returns the first occurrence ofneedle
inhaystack
, case-sensitively. If not found, returns -1. -
Format:
Pos(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePos() {
var (
haystack = `Hello World`
needle = `World`
result = gstr.Pos(haystack, needle)
)
fmt.Println(result)
// Output:
// 6
}
PosRune
-
Description:
PosRune
functions similarly toPos
, but supportshaystack
andneedle
asunicode
strings. -
Format:
PosRune(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosRune() {
var (
haystack = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架`
needle = `Go`
posI = gstr.PosRune(haystack, needle)
posR = gstr.PosRRune(haystack, needle)
)
fmt.Println(posI)
fmt.Println(posR)
// Output:
// 0
// 22
}
PosI
-
Description:
PosI
returns the first occurrence ofneedle
inhaystack
, case-insensitively. If not found, returns -1. -
Format:
PosI(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosI() {
var (
haystack = `goframe is very, very easy to use`
needle = `very`
posI = gstr.PosI(haystack, needle)
posR = gstr.PosR(haystack, needle)
)
fmt.Println(posI)
fmt.Println(posR)
// Output:
// 11
// 17
}
PosRuneI
-
Description:
PosRuneI
functions similarly toPosI
, but supportshaystack
andneedle
asunicode
strings. -
Format:
PosIRune(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosIRune() {
{
var (
haystack = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架`
needle = `高性能`
startOffset = 10
result = gstr.PosIRune(haystack, needle, startOffset)
)
fmt.Println(result)
}
{
var (
haystack = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架`
needle = `高性能`
startOffset = 30
result = gstr.PosIRune(haystack, needle, startOffset)
)
fmt.Println(result)
}
// Output:
// 14
// -1
}
PosR
-
Description:
PosR
returns the last occurrence ofneedle
inhaystack
, case-sensitively. If not found, returns -1. -
Format:
PosR(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosR() {
var (
haystack = `goframe is very, very easy to use`
needle = `very`
posI = gstr.PosI(haystack, needle)
posR = gstr.PosR(haystack, needle)
)
fmt.Println(posI)
fmt.Println(posR)
// Output:
// 11
// 17
}
PosRuneR
-
Description:
PosRuneR
functions similarly toPosR
, but supportshaystack
andneedle
asunicode
strings. -
Format:
PosRRune(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosRRune() {
var (
haystack = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架`
needle = `Go`
posI = gstr.PosIRune(haystack, needle)
posR = gstr.PosRRune(haystack, needle)
)
fmt.Println(posI)
fmt.Println(posR)
// Output:
// 0
// 22
}
PosRI
-
Description:
PosRI
returns the last occurrence ofneedle
inhaystack
, case-insensitively. If not found, returns -1. -
Format:
PosRI(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosRI() {
var (
haystack = `goframe is very, very easy to use`
needle = `VERY`
posI = gstr.PosI(haystack, needle)
posR = gstr.PosRI(haystack, needle)
)
fmt.Println(posI)
fmt.Println(posR)
// Output:
// 11
// 17
}
PosRIRune
-
Description:
PosRIRune
functions similarly toPosRI
, but supportshaystack
andneedle
asunicode
strings. -
Format:
PosRIRune(haystack, needle string, startOffset ...int) int
- Example:
func ExamplePosRIRune() {
var (
haystack = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架`
needle = `GO`
posI = gstr.PosIRune(haystack, needle)
posR = gstr.PosRIRune(haystack, needle)
)
fmt.Println(posI)
fmt.Println(posR)
// Output:
// 0
// 22
}
Find and Replace
Replace
-
Description:
Replace
returns a new string wheresearch
inorigin
is replaced byreplace
.search
is case-sensitive. -
Format:
Replace(origin, search, replace string, count ...int) string
- Example:
func ExampleReplace() {
var (
origin = `golang is very nice!`
search = `golang`
replace = `goframe`
result = gstr.Replace(origin, search, replace)
)
fmt.Println(result)
// Output:
// goframe is very nice!
}
ReplaceI
-
Description:
ReplaceI
returns a new string wheresearch
inorigin
is replaced byreplace
.search
is case-insensitive. -
Format:
ReplaceI(origin, search, replace string, count ...int) string
- Example:
func ExampleReplaceI() {
var (
origin = `golang is very nice!`
search = `GOLANG`
replace = `goframe`
result = gstr.ReplaceI(origin, search, replace)
)
fmt.Println(result)
// Output:
// goframe is very nice!
}
ReplaceByArray
-
Description:
ReplaceByArray
returns a new string whereorigin
is sequentially replaced with pairs(search, replace)
from an array, case-sensitively. -
Format:
ReplaceByArray(origin string, array []string) string
- Example:
func ExampleReplaceByArray() {
{
var (
origin = `golang is very nice`
array = []string{"lang", "frame"}
result = gstr.ReplaceByArray(origin, array)
)
fmt.Println(result)
}
{
var (
origin = `golang is very good`
array = []string{"golang", "goframe", "good", "nice"}
result = gstr.ReplaceByArray(origin, array)
)
fmt.Println(result)
}
// Output:
// goframe is very nice
// goframe is very nice
}
ReplaceIByArray
-
Description:
ReplaceIByArray
returns a new string whereorigin
is sequentially replaced with pairs(search, replace)
from an array, case-insensitively. -
Format:
ReplaceIByArray(origin string, array []string) string
- Example:
func ExampleReplaceIByArray() {
var (
origin = `golang is very Good`
array = []string{"Golang", "goframe", "GOOD", "nice"}
result = gstr.ReplaceIByArray(origin, array)
)
fmt.Println(result)
// Output:
// goframe is very nice
}
ReplaceByMap
-
Description:
ReplaceByMap
returns a new string where keys inmap
are replaced with values inorigin
, case-sensitively. -
Format:
ReplaceByMap(origin string, replaces map[string]string) string
- Example:
func ExampleReplaceByMap() {
{
var (
origin = `golang is very nice`
replaces = map[string]string{
"lang": "frame",
}
result = gstr.ReplaceByMap(origin, replaces)
)
fmt.Println(result)
}
{
var (
origin = `golang is very good`
replaces = map[string]string{
"golang": "goframe",
"good": "nice",
}
result = gstr.ReplaceByMap(origin, replaces)
)
fmt.Println(result)
}
// Output:
// goframe is very nice
// goframe is very nice
}
ReplaceIByMap
-
Description:
ReplaceIByMap
returns a new string where keys inmap
are replaced with values inorigin
, case-insensitively. -
Format:
ReplaceIByMap(origin string, replaces map[string]string) string
- Example:
func ExampleReplaceIByMap() {
var (
origin = `golang is very nice`
replaces = map[string]string{
"Lang": "frame",
}
result = gstr.ReplaceIByMap(origin, replaces)
)
fmt.Println(result)
// Output:
// goframe is very nice
}
Substring Extraction
Str
-
Description:
Str
returns the substring from the first occurrence ofneedle
to the end ofhaystack
(includingneedle
itself). -
Format:
Str(haystack string, needle string) string
- Example:
func ExampleStr() {
var (
haystack = `xxx.jpg`
needle = `.`
result = gstr.Str(haystack, needle)
)
fmt.Println(result)
// Output:
// .jpg
}
StrEx
-
Description:
StrEx
returns the substring from the first occurrence ofneedle
to the end ofhaystack
(excludingneedle
itself). -
Format:
StrEx(haystack string, needle string) string
- Example:
func ExampleStrEx() {
var (
haystack = `https://goframe.org/index.html?a=1&b=2`
needle = `?`
result = gstr.StrEx(haystack, needle)
)
fmt.Println(result)
// Output:
// a=1&b=2
}
StrTill
-
Description:
StrTill
returns the substring from the start ofhaystack
to the first occurrence ofneedle
(includingneedle
itself). -
Format:
StrTill(haystack string, needle string) string
- Example:
func ExampleStrTill() {
var (
haystack = `https://goframe.org/index.html?test=123456`
needle = `?`
result = gstr.StrTill(haystack, needle)
)
fmt.Println(result)
// Output:
// https://goframe.org/index.html?
}
StrTillEx
-
Description:
StrTillEx
returns the substring from the start ofhaystack
to the first occurrence ofneedle
(excludingneedle
itself). -
Format:
StrTillEx(haystack string, needle string) string
- Example:
func ExampleStrTillEx() {
var (
haystack = `https://goframe.org/index.html?test=123456`
needle = `?`
result = gstr.StrTillEx(haystack, needle)
)
fmt.Println(result)
// Output:
// https://goframe.org/index.html
}
SubStr
-
Description:
SubStr
returns a new substring fromstr
starting atstart
with lengthlength
. Parameterlength
is optional and defaults to the length ofstr
. -
Format:
SubStr(str string, start int, length ...int) (substr string)
- Example:
func ExampleSubStr() {
var (
str = `1234567890`
start = 0
length = 4
subStr = gstr.SubStr(str, start, length)
)
fmt.Println(subStr)
// Output:
// 1234
}
SubStrRune
-
Description:
SubStrRune
returns a new substring fromunicode
stringstr
starting atstart
with lengthlength
. Parameterlength
is optional and defaults to the length ofstr
. -
Format:
SubStrRune(str string, start int, length ...int) (substr string)
- Example:
func ExampleSubStrRune() {
var (
str = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架。`
start = 14
length = 3
subStr = gstr.SubStrRune(str, start, length)
)
fmt.Println(subStr)
// Output:
// 高性能
}
StrLimit
-
Description:
StrLimit
takes a substring from the beginning ofstr
with lengthlength
, addssuffix...
, and returns the new string. -
Format:
StrLimit(str string, length int, suffix ...string) string
- Example:
func ExampleStrLimit() {
var (
str = `123456789`
length = 3
suffix = `...`
result = gstr.StrLimit(str, length, suffix)
)
fmt.Println(result)
// Output:
// 123...
}
StrLimitRune
-
Description:
StrLimitRune
takes a substring from the beginning ofunicode
stringstr
with lengthlength
, addssuffix...
, and returns the new string. -
Format:
StrLimitRune(str string, length int, suffix ...string) string
- Example:
func ExampleStrLimitRune() {
var (
str = `GoFrame是一款模块化、高性能、企业级的Go基础开发框架。`
length = 17
suffix = "..."
result = gstr.StrLimitRune(str, length, suffix)
)
fmt.Println(result)
// Output:
// GoFrame是一款模块化、高性能...
}
SubStrFrom
-
Description:
SubStrFrom
returns the substring from the first occurrence ofneed
to the end ofstr
(includingneed
). -
Format:
SubStrFrom(str string, need string) (substr string)
- Example:
func ExampleSubStrFrom() {
var (
str = "我爱GoFrameGood"
need = `爱`
)
fmt.Println(gstr.SubStrFrom(str, need))
// Output:
// 爱GoFrameGood
}
SubStrFromEx
-
Description:
SubStrFromEx
returns the substring from the first occurrence ofneed
to the end ofstr
(excludingneed
). -
Format:
SubStrFromEx(str string, need string) (substr string)
- Example:
func ExampleSubStrFromEx() {
var (
str = "我爱GoFrameGood"
need = `爱`
)
fmt.Println(gstr.SubStrFromEx(str, need))
// Output:
// GoFrameGood
}
SubStrFromR
-
Description:
SubStrFromR
returns the substring from the last occurrence ofneed
to the end ofstr
(includingneed
). -
Format:
SubStrFromR(str string, need string) (substr string)
- Example:
func ExampleSubStrFromR() {
var (
str = "我爱GoFrameGood"
need = `Go`
)
fmt.Println(gstr.SubStrFromR(str, need))
// Output:
// Good
}
SubStrFromREx
-
Description:
SubStrFromREx
returns the substring from the last occurrence ofneed
to the end ofstr
(excludingneed
). -
Format:
SubStrFromREx(str string, need string) (substr string)
- Example:
func ExampleSubStrFromREx() {
var (
str = "我爱GoFrameGood"
need = `Go`
)
fmt.Println(gstr.SubStrFromREx(str, need))
// Output:
// od
}
Character/Substring Filtering
Trim
-
Description:
Trim
removes spaces (or other characters) from the beginning and end of a string. The optional parametercharacterMask
specifies additional characters to trim. -
Format:
Trim(str string, characterMask ...string) string
- Example:
func ExampleTrim() {
var (
str = `*Hello World*`
characterMask = "*d"
result = gstr.Trim(str, characterMask)
)
fmt.Println(result)
// Output:
// Hello Worl
}
TrimStr
-
Description:
TrimStr
removes allcut
strings from the beginning and end of a string (does not remove leading or trailing whitespace). -
Format:
TrimStr(str string, cut string, count ...int) string
- Example:
func ExampleTrimStr() {
var (
str = `Hello World`
cut = "World"
count = -1
result = gstr.TrimStr(str, cut, count)
)
fmt.Println(result)
// Output:
// Hello
}
TrimLeft
-
Description:
TrimLeft
removes spaces (or other characters) from the beginning of a string. -
Format:
TrimLeft(str string, characterMask ...string) string
- Example:
func ExampleTrimLeft() {
var (
str = `*Hello World*`
characterMask = "*"
result = gstr.TrimLeft(str, characterMask)
)
fmt.Println(result)
// Output:
// Hello World*
}
TrimLeftStr
-
Description:
TrimLeftStr
removescount
occurrences of thecut
string from the beginning of a string (does not remove leading whitespace). -
Format:
TrimLeftStr(str string, cut string, count ...int) string
- Example:
func ExampleTrimLeftStr() {
var (
str = `**Hello World**`
cut = "*"
count = 1
result = gstr.TrimLeftStr(str, cut, count)
)
fmt.Println(result)
// Output:
// *Hello World**
}
TrimRight
-
Description:
TrimRight
removes spaces (or other characters) from the end of a string. -
Format:
TrimRight(str string, characterMask ...string) string
- Example:
func ExampleTrimRight() {
var (
str = `**Hello World**`
characterMask = "*def" // []byte{"*", "d", "e", "f"}
result = gstr.TrimRight(str, characterMask)
)
fmt.Println(result)
// Output:
// **Hello Worl
}
TrimRightStr
-
Description:
TrimRightStr
removescount
occurrences of thecut
string from the end of a string (does not remove trailing whitespace). -
Format:
TrimRightStr(str string, cut string, count ...int) string
- Example:
func ExampleTrimRightStr() {
var (
str = `Hello World!`
cut = "!"
count = -1
result = gstr.TrimRightStr(str, cut, count)
)
fmt.Println(result)
// Output:
// Hello World
}
TrimAll
-
Description:
TrimAll
removes all spaces (or other characters) andcharacterMask
characters from stringstr
. -
Format:
TrimAll(str string, characterMask ...string) string
- Example:
func ExampleTrimAll() {
var (
str = `*Hello World*`
characterMask = "*"
result = gstr.TrimAll(str, characterMask)
)
fmt.Println(result)
// Output:
// HelloWorld
}
HasPrefix
-
Description:
HasPrefix
returns whethers
starts withprefix
. -
Format:
HasPrefix(s, prefix string) bool
- Example:
func ExampleHasPrefix() {
var (
s = `Hello World`
prefix = "Hello"
result = gstr.HasPrefix(s, prefix)
)
fmt.Println(result)
// Output:
// true
}
HasSuffix
-
Description:
HasSuffix
returns whethers
ends withsuffix
. -
Format:
HasSuffix(s, suffix string) bool
- Example:
func ExampleHasSuffix() {
var (
s = `my best love is goframe`
prefix = "goframe"
result = gstr.HasSuffix(s, prefix)
)
fmt.Println(result)
// Output:
// true
}
Version Comparison
CompareVersion
-
Description:
CompareVersion
comparesa
andb
as standardGNU
versions. -
Format:
CompareVersion(a, b string) int
- Example:
func ExampleCompareVersion() {
fmt.Println(gstr.CompareVersion("v2.11.9", "v2.10.8"))
fmt.Println(gstr.CompareVersion("1.10.8", "1.19.7"))
fmt.Println(gstr.CompareVersion("2.8.beta", "2.8"))
// Output:
// 1
// -1
// 0
}
CompareVersionGo
-
Description:
CompareVersionGo
comparesa
andb
as standardGolang
versions. -
Format:
CompareVersionGo(a, b string) int
- Example:
func ExampleCompareVersionGo() {
fmt.Println(gstr.CompareVersionGo("v2.11.9", "v2.10.8"))
fmt.Println(gstr.CompareVersionGo("v4.20.1", "v4.20.1+incompatible"))
fmt.Println(gstr.CompareVersionGo(
"v0.0.2-20180626092158-b2ccc119800e",
"v1.0.1-20190626092158-b2ccc519800e",
))
// Output:
// 1
// 1
// -1
}
Similarity Calculation
Levenshtein
-
Description:
Levenshtein
calculates theLevenshtein
distance between two strings. -
Format:
Levenshtein(str1, str2 string, costIns, costRep, costDel int) int
- Example:
func ExampleLevenshtein() {
var (
str1 = "Hello World"
str2 = "hallo World"
costIns = 1
costRep = 1
costDel = 1
result = gstr.Levenshtein(str1, str2, costIns, costRep, costDel)
)
fmt.Println(result)
// Output:
// 2
}
SimilarText
-
Description:
SimilarText
calculates the similarity between two strings. -
Format:
SimilarText(first, second string, percent *float64) int
- Example:
func ExampleSimilarText() {
var (
first = `AaBbCcDd`
second = `ad`
percent = 0.80
result = gstr.SimilarText(first, second, &percent)
)
fmt.Println(result)
// Output:
// 2
}
Soundex
-
Description:
Soundex
is used to calculate theSoundex
key for a string. -
Format:
Soundex(str string) string
- Example:
func ExampleSoundex() {
var (
str1 = `Hello`
str2 = `Hallo`
result1 = gstr.Soundex(str1)
result2 = gstr.Soundex(str2)
)
fmt.Println(result1, result2)
// Output:
// H400 H400
}