Documentation
¶
Overview ¶
Package strutil provides string utilities for utf8 encoded strings. It is complemantary to builtin strings package.
Index ¶
- Constants
- Variables
- func Align(str string, typ string, width int) string
- func AlignCenter(str string, width int) string
- func AlignLeft(str string, width int) string
- func AlignRight(str string, width int) string
- func Box(content string, width int, align string) (string, error)
- func Center(str string, width int) string
- func CountWords(str string) int
- func CustomBox(content string, width int, align string, chars Box9Slice) (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 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, int, error)
- func ReplaceAllToOne(str string, from []string, to string) string
- func Reverse(str string) string
- func Slugify(str string) string
- func SlugifySpecial(str string, delimeter string) string
- func Splice(str string, newStr string, start int, end int) string
- func SplitCamelCase(str string) []string
- func Substring(str string, start int, end int) string
- func Summary(str string, length int, end string) string
- func ToCamelCase(str string) string
- func ToSnakeCase(str string) string
- func Words(str string) []string
- func Wordwrap(str string, colLen int, breakLongWords bool) string
- type Box9Slice
Examples ¶
Constants ¶
const ( AlignTypeCenter = "center" AlignTypeLeft = "left" AlignTypeRight = "right" )
Align type to use with align function
Variables ¶
var SpecialAccentReplacer = strings.NewReplacer(
"ı", "i",
"İ", "I",
"ð", "o",
"ø", "o",
"Ø", "O",
"ß", "ss",
"ł", "l",
"æ", "a")
SpecialAccentReplacer is a string.Replacer for removing accents for special characters like Turkish "ı" or "İ"
var UTF8Len = utf8.RuneCountInString
UTF8Len 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 "typ" which should be one of
- strutil.AlignTypeCenter
- strutil.AlignTypeLeft
- strutil.AlignTypeRight
Example ¶
fmt.Println(Align(" lorem \n ipsum ", AlignTypeRight, 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 str to the left. It actually trims and right pads all the lines in the text with space to the size of width.
Example ¶
aligned := AlignLeft(" lorem\n ipsum", 10)
fmt.Println(strings.Replace(aligned, " ", ".", -1))
Output: lorem..... ipsum.....
func AlignRight ¶
AlignRight aligns str to the right. It actually 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 Box ¶
Box 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: Box("Hello World", 20, AligntTypeCenter)
Example ¶
output, _ := Box("Hello World", 20, AlignTypeCenter)
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, _ := Box(text, 30, AlignTypeLeft) 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 Center ¶
Center centers the text by adding spaces to the left and right.
Example ¶
fmt.Println("'" + Center("lorem", 9) + "'")
Output: ' lorem '
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 CustomBox ¶
CustomBox 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: strutil.DefaultBox9Slice or strutil.SimpleBox9Slice. CustomBox wrap the lines with strutil.WordWrap before placing it.
Usage: CustomBox("Hello World", 20, AligntTypeCenter, SimpleBox9Slice)
Example ¶
output, _ := CustomBox("Hello World", 20, AlignTypeCenter, DefaultBox9Slice)
fmt.Println(output)
Output: ┌──────────────────┐ │ Hello World │ └──────────────────┘
func ExpandTabs ¶
ExpandTabs convert tabs the spaces with the length of count
func Indent ¶
Indent indents every line of string str with the left parameter For empty strings it returns "". 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 "\n" and runs the 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 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))
func RemoveAccents ¶
RemoveAccents removes accents from the letters. The resuting string only has the letters from English alphabet. taken from https://blog.golang.org/normalization
Example ¶
output, _, _ := RemoveAccents("ßąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșşšŝťțţŭùúüűûñÿýçżźž")
fmt.Println(output)
Output: ssaaaaaaaaaccceeeeeghiiiijllnnoooooooossssstttuuuuuunyyczzz
func ReplaceAllToOne ¶
ReplaceAllToOne replaces every string in the from to the string "to"
Example ¶
fmt.Println(ReplaceAllToOne("lorem", []string{"lo", "em"}, "x"))
Output: xrx
func Reverse ¶
Reverse reverses the string
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 ¶
fmt.Println(Slugify("We löve Motörhead"))
Output: we-love-motorhead
func SlugifySpecial ¶
SlugifySpecial converts a string to a slug with the delimeter. It removes accents, converts string to lower case, remove the characters which are not letters or numbers and replaces spaces with the delimeter.
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.Splice 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 SplitCamelCase ¶
SplitCamelCase splits and returns words in camelCase format.
Example:
SplitCamelCase("loremIpsum")
//Output
{"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.
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
Example ¶
fmt.Println(Substring("Υπάρχουν", 1, 4))
Output: πάρ
Example (TillTheEnd) ¶
fmt.Println(Substring("Υπάρχουν", 1, 0))
Output: πάρχουν
func Summary ¶ added in v0.2.0
Summary cuts the string to a new length and adds the "end" to it It only break up the words by spaces
Example ¶
fmt.Println(Summary("Lorem ipsum dolor sit amet.", 12, "..."))
Output: Lorem ipsum...
func ToCamelCase ¶
ToCamelCase converts str 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")
//Outputs: camelCase
ToCamelCase("inside dynaMIC-HTML")
//Outputs: insideDynaMIC-HTML
Example ¶
fmt.Println(ToCamelCase("long live motörhead"))
Output: longLiveMotörhead
func ToSnakeCase ¶
ToSnakeCase converts str into snake_case formatted string. In the process it trims the string and the 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")
//Outputs: snake_case
Example ¶
fmt.Println(ToSnakeCase("Lorem Ipsum"))
Output: lorem_ipsum
func Words ¶ added in v0.2.0
Words returns the words inside the text. - Numbers are counted as words - If they are inside a word these punctuations don't break a word: ', -, _
func Wordwrap ¶
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 Box9Slice ¶
type Box9Slice struct {
Top string
TopRight string
Right string
BottomRight string
Bottom string
BottomLeft string
Left string
TopLeft string
}
Box9Slice is used by Box functions to draw frames around text content by defining the corner and edge characters. See DefaultBox9Slice for an example
var DefaultBox9Slice Box9Slice = Box9Slice{
Top: "─",
TopRight: "┐",
Right: "│",
BottomRight: "┘",
Bottom: "─",
BottomLeft: "└",
Left: "│",
TopLeft: "┌",
}
DefaultBox9Slice defines the character object to use with "CustomBox". It is used as Box9Slice object in "Box" function.
Usage: CustomBox("Hello World", 20, AligntTypeCenter, DefaultBox9Slice)
Outputs:
┌──────────────────┐ │ Hello World │ └──────────────────┘
</code>
var SimpleBox9Slice Box9Slice = Box9Slice{
Top: "-",
TopRight: "+",
Right: "|",
BottomRight: "+",
Bottom: "-",
BottomLeft: "+",
Left: "|",
TopLeft: "+",
}
SimpleBox9Slice defines a character set to use with CustomBox. It uses only simple ASCII chaaracters
Usage: CustomBox("Hello World", 20, AligntTypeCenter, SimpleBox9Slice)
Outputs:
+------------------+ | Hello World | +------------------+