Documentation
¶
Overview ¶
Package strutil provides string utilities for utf8 encoded strings. It is complemantary to builtin strings package.
Index ¶
- Variables
- func Align(str string, alignTo AlignType, width int) string
- func AlignCenter(str string, width int) string
- func AlignLeft(str string) string
- func AlignRight(str string, width int) string
- func CenterText(str string, width int) string
- func CountWords(str string) int
- func DrawBox(content string, width int, align AlignType) (string, error)
- func DrawCustomBox(content string, width int, align AlignType, chars Box9Slice, strNewLine string) (string, error)
- func ExpandTabs(str string, count int) string
- func Indent(str string, left string) string
- func IsASCII(s string) bool
- func MapLines(str string, fn func(string) string) string
- func MustSubstring(str string, start int, end int) string
- func OSNewLine() string
- func Pad(str string, width int, leftPad string, rightPad string) string
- func PadLeft(str string, width int, pad string) string
- func PadRight(str string, width int, pad string) string
- func Random(strSet string, length int) (string, error)
- func RemoveAccents(str string) string
- func ReplaceAllToOne(str string, from []string, to string) string
- func Reverse(s string) string
- func Slugify(str string) string
- func SlugifySpecial(str string, delimiter string) string
- func Splice(str string, newStr string, start int, end int) string
- func SplitAndMap(str string, split string, fn func(string) string) string
- func SplitCamelCase(str string) []string
- func Substring(str string, start int, end int) (string, error)
- func Summary(str string, length int, end string) string
- func Tile(pattern string, length int) string
- func ToCamelCase(str string) string
- func ToSnakeCase(str string) string
- func WordWrap(str string, colLen int, breakLongWords bool) string
- func Words(str string) []string
- type AlignType
- type Box9Slice
Examples ¶
- Align
- AlignCenter
- AlignLeft
- AlignRight
- CountWords
- DrawBox
- DrawBox (Long)
- DrawCustomBox
- ExpandTabs
- Indent
- MapLines
- MustSubstring
- MustSubstring (TillTheEnd)
- Pad
- PadLeft
- PadRight
- Random
- RemoveAccents
- ReplaceAllToOne
- Reverse
- Slugify
- SlugifySpecial
- Splice
- SplitCamelCase
- Summary
- ToCamelCase
- ToSnakeCase
- WordWrap
Constants ¶
This section is empty.
Variables ¶
var Len = utf8.RuneCountInString
Len is an alias of utf8.RuneCountInString which returns the number of runes in s. Erroneous and short encodings are treated as single runes of width 1 byte.
Functions ¶
func Align ¶
Align aligns string to the "alignTo" which should be one of - strutil.Center - strutil.Left - strutil.Right
Example ¶
fmt.Println(Align(" lorem \n ipsum ", Right, 10))
Output: lorem ipsum
func AlignCenter ¶
AlignCenter centers str. It trims and then centers all the lines in the text with space
Example ¶
text := AlignCenter("lorem\nipsum", 9) fmt.Println(strings.Replace(text, " ", ".", -1))
Output: ..lorem.. ..ipsum..
func AlignLeft ¶
AlignLeft aligns string to the left. To achieve that it left trims every line.
Example ¶
fmt.Println(AlignLeft(" lorem\n ipsum"))
Output: lorem ipsum
func AlignRight ¶
AlignRight aligns string to the right. It trims and left pads all the lines in the text with space to the size of width.
Example ¶
fmt.Println(AlignRight(" lorem \n ipsum ", 10))
Output: lorem ipsum
func CenterText ¶ added in v0.3.0
CenterText centers the text by adding spaces to the left and right. It assumes the text is one line. For multiple lines use AlignCenter.
func CountWords ¶
CountWords count the words, It uses the same base function with 'Words' function. only difference is CountWords doesn't allocate an array so it is faster and more memory efficient
Example ¶
fmt.Println(CountWords("It is not known exactly!"))
Output: 5
func DrawBox ¶ added in v0.3.0
DrawBox creates a frame with "content" in it. DefaultBox9Slice object is used to define characters in the frame. "align" sets the alignment of the content. It must be one of the strutil.AlignType constants.
Usage:
DrawBox("Hello World", 20, Center)
Outputs:
┌──────────────────┐ │ Hello World │ └──────────────────┘
Example ¶
output, _ := DrawBox("Hello World", 20, Center) fmt.Println(output)
Output: ┌──────────────────┐ │ Hello World │ └──────────────────┘
Example (Long) ¶
text := `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.` output, _ := DrawBox(text, 30, Left) fmt.Println(output)
Output: ┌────────────────────────────┐ │Lorem ipsum dolor sit amet, │ │consectetur adipiscing elit,│ │sed do eiusmod tempor │ │incididunt ut labore et │ │dolore magna aliqua. Ut enim│ │ad minim veniam, quis │ │nostrud exercitation ullamco│ │laboris nisi ut aliquip ex │ │ea commodo consequat. │ └────────────────────────────┘
func DrawCustomBox ¶ added in v0.3.0
func DrawCustomBox(content string, width int, align AlignType, chars Box9Slice, strNewLine string) (string, error)
DrawCustomBox creates a frame with "content" in it. Characters in the frame is specified by "chars". "align" sets the alignment of the content. It must be one of the strutil.AlignType constants. There are 2 premade Box9Slice objects that can be retrieved by strutil.DefaultBox9Slice() or strutil.SimpleBox9Slice()
Usage:
DrawCustomBox("Hello World", 20, Center, SimpleBox9Slice(), "\n")
Outputs:
+------------------+ | Hello World | +------------------+
Example ¶
output, _ := DrawCustomBox("Hello World", 20, Center, DefaultBox9Slice(), "\n") fmt.Println(output)
Output: ┌──────────────────┐ │ Hello World │ └──────────────────┘
func ExpandTabs ¶
ExpandTabs converts tabs to the spaces. count specifies the number of spaces
Example ¶
fmt.Printf("%s", ExpandTabs("\tlorem\n\tipsum", 2))
Output: lorem ipsum
func Indent ¶
Indent indents every line of string str with the left parameter Empty lines are indented too.
Example ¶
fmt.Println(Indent("Lorem ipsum\ndolor sit amet", " > "))
Output: > Lorem ipsum > dolor sit amet
func IsASCII ¶ added in v0.2.0
IsASCII checks if all the characters in string are in standard ASCII table It is taken from strings.Fields function
func MapLines ¶
MapLines runs function fn on every line of the string. It splits the string by new line character ("\n"), then runs 'fn' for every line and returns the new string by combining these lines with "\n"
Example ¶
fmt.Println(MapLines("Lorem\nIpsum", strings.ToUpper))
Output: LOREM IPSUM
func MustSubstring ¶ added in v0.3.0
MustSubstring gets a part of the string between start and end. If end is 0, end is taken as the length of the string.
It is UTF8 safe version of using slice notations in strings. It panics when the indexes are out of range. String length can be get with UTF8Len function before using Substring. You can use "Substring" if you prefer errors to panics.
Example ¶
fmt.Println(MustSubstring("Υπάρχουν", 1, 4))
Output: πάρ
Example (TillTheEnd) ¶
fmt.Println(MustSubstring("Υπάρχουν", 1, 0))
Output: πάρχουν
func OSNewLine ¶ added in v0.3.0
func OSNewLine() string
OSNewLine returns operating system's default new line character. It is \r\n in Windowns and \n elsewhere.
func Pad ¶
Pad left and right pads a string str with leftPad and rightPad. The string is padded to the size of width.
Example ¶
fmt.Println(Pad("lorem", 9, "-", "-"))
Output: --lorem--
func PadLeft ¶
PadLeft left pads a string str with "pad". The string is padded to the size of width.
Example ¶
fmt.Println(PadLeft("lorem", 10, "-"))
Output: -----lorem
func PadRight ¶
PadRight right pads a string str with "pad". The string is padded to the size of width.
Example ¶
fmt.Println(PadRight("lorem", 10, "-"))
Output: lorem-----
func Random ¶ added in v0.2.0
Random creates new string based on strSet. It uses crypto/rand as the random number generator. error is the one returned by rand.Int
Example ¶
fmt.Println(Random("abcdefghik", 5))
Output:
func RemoveAccents ¶
RemoveAccents removes accents from the string. The resulting string only has the letters from English alphabet. For example, "résumé" becomes "resume". It may not work as expected for some specific letters. Please create an issue for these situations.
Example ¶
output := RemoveAccents("ßąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșşšŝťțţŭùúüűûñÿýçżźž") fmt.Println(output)
Output: ssaaaaaaaaeaccceeeeeghiiiijllnnoooooodjoessssstttuuuuuunyyczzz
func ReplaceAllToOne ¶
ReplaceAllToOne replaces every string in the "from" with the string "to"
Example ¶
fmt.Println(ReplaceAllToOne("lorem", []string{"lo", "em"}, "x"))
Output: xrx
func Reverse ¶
Reverse reverses the string Copied from here https://stackoverflow.com/a/20225618/153570
Example ¶
fmt.Println(Reverse("επαγγελματίες"))
Output: ςείταμλεγγαπε
func Slugify ¶
Slugify converts a string to a slug which is useful in URLs, filenames. It removes accents, converts to lower case, remove the characters which are not letters or numbers and replaces spaces with "-".
Example:
strutil.Slugify("'We löve Motörhead'") //Output: we-love-motorhead
Normalzation is done with strutil.ReplaceAccents function using a rune replacement map You can use the following code for better normalization before strutil.Slugify()
str := "'We löve Motörhead'" t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) str = transform.String(t, str) //We love Motorhead
Slugify doesn't support transliteration. You should use a transliteration library before Slugify like github.com/rainycape/unidecode
Example:
import "github.com/rainycape/unidecode" str := unidecode.Unidecode("你好, world!") strutil.Slugify(str) //Output: ni-hao-world
Example ¶
fmt.Println(Slugify("We löve Motörhead"))
Output: we-love-motorhead
func SlugifySpecial ¶
SlugifySpecial converts a string to a slug with the delimiter. It removes accents, converts string to lower case, remove the characters which are not letters or numbers and replaces spaces with the delimiter.
Example:
strutil.SlugifySpecial("'We löve Motörhead'", "-") //Output: we-love-motorhead
SlugifySpecial doesn't support transliteration. You should use a transliteration library before SlugifySpecial like github.com/rainycape/unidecode
Example:
import "github.com/rainycape/unidecode" str := unidecode.Unidecode("你好, world!") strutil.SlugifySpecial(str, "-") //Output: ni-hao-world
Example ¶
fmt.Println(SlugifySpecial("We löve Motörhead", "_"))
Output: we_love_motorhead
func Splice ¶ added in v0.2.0
Splice insert a new string in place of the string between start and end indexes. It is based on runes so start and end indexes are rune based indexes. It can be used to remove a part of string by giving newStr as empty string
Example ¶
fmt.Println(Splice("Lorem", "ipsum", 2, 3))
Output: Loipsumem
func SplitAndMap ¶ added in v0.3.0
SplitAndMap splits the string and runs the function fn on every part
func SplitCamelCase ¶
SplitCamelCase splits and returns words in camelCase format.
Example:
SplitCamelCase("loremIpsum") //Output []string{"lorem", "Ipsum"}
Example ¶
fmt.Printf("%#v\n", SplitCamelCase("binaryJSONAbstractWriter"))
Output: []string{"binary", "JSON", "Abstract", "Writer"}
func Substring ¶
Substring gets a part of the string between start and end. If end is 0, end is taken as the length of the string.
MustSubstring can be used for the cases where the boundaries are wwll known and/or panics are acceptable
It is UTF8 safe version of using slice notations in strings.
func Summary ¶ added in v0.2.0
Summary cuts the string to a new length and adds the "end" to it It only breaks up the words by spaces. See "unicode.IsSpace" for which characters are accepted as spaces
Example ¶
fmt.Println(Summary("Lorem ipsum dolor sit amet.", 12, "..."))
Output: Lorem ipsum...
func Tile ¶ added in v0.3.0
Tile repeats the pattern until the result reaches the 'length' It returns empty string if the pattern is "" or length <= 0
func ToCamelCase ¶
ToCamelCase converts string into camelCase formatted string after trimming it. It doesn't change the cases of letters except the first letters of the words. ToCamelCase also doesn't remove punctions or such characters and it separates words only with " "
Example:
ToCamelCase("camel case") //Output: camelCase ToCamelCase("inside dynaMIC-HTML") //Output: insideDynaMIC-HTML
Example ¶
fmt.Println(ToCamelCase("long live motörhead"))
Output: longLiveMotörhead
func ToSnakeCase ¶
ToSnakeCase converts string into snake_case formatted string. In the process it trims the string and then converts characters into lowercase. Only space " " character is converted into underscore "_". If you have other characters you should convert them into spaces before calling ToSnakeCase
Example:
ToSnakeCase("Snake Case") //Output: snake_case
Example ¶
fmt.Println(ToSnakeCase("Lorem Ipsum"))
Output: lorem_ipsum
func WordWrap ¶ added in v0.3.0
WordWrap wraps the given string str based on colLen as max line width. if breakLongWords is true, it breaks the words which are longer than colLen.
Notes: - WordWrap doesn't trim the lines, except it trims the left side of the new line created by breaking a long line. - Tabs should be converted to space before using WordWrap.
Example ¶
fmt.Println(WordWrap("Lorem ipsum, dolor sit amet.", 15, false))
Output: Lorem ipsum, dolor sit amet.
Types ¶
type AlignType ¶ added in v0.3.0
type AlignType string
AlignType text align variable like center or left
type Box9Slice ¶
type Box9Slice struct { Top string TopRight string Right string BottomRight string Bottom string BottomLeft string Left string TopLeft string }
Box9Slice is used by DrawBox functions to draw frames around text content by defining the corner and edge characters. See DefaultBox9Slice for an example
func DefaultBox9Slice ¶
func DefaultBox9Slice() Box9Slice
DefaultBox9Slice defines the character object to use with "CustomBox". It is used as Box9Slice object in "DrawBox" function.
Usage: DrawCustomBox("Hello World", 20, AligntTypeCenter, DefaultBox9Slice())
Outputs: <code>
┌──────────────────┐ │ Hello World │ └──────────────────┘
</code>
func SimpleBox9Slice ¶
func SimpleBox9Slice() Box9Slice
SimpleBox9Slice defines a character set to use with DrawCustomBox. It uses only simple ASCII characters
Usage:
DrawCustomBox("Hello World", 20, Center, SimpleBox9Slice(), "\n")
Outputs:
+------------------+ | Hello World | +------------------+