strutil: github.com/ozgio/strutil Index | Examples | Files

package strutil

import "github.com/ozgio/strutil"

Package strutil provides string utilities for utf8 encoded strings. It is complemantary to builtin strings package.

Index

Examples

Package Files

align.go case.go doc.go drawbox.go expandtabs.go indent.go isascii.go map.go newline.go normalization.go pad.go random.go removeaccents.go replace.go reverse.go slugify.go substring.go summary.go tile.go util.go words.go wordwrap.go

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.

func Align Uses

func Align(str string, alignTo AlignType, width int) string

Align aligns string to the "alignTo" which should be one of - strutil.Center - strutil.Left - strutil.Right

Code:

fmt.Println(Align("  lorem  \n  ipsum  ", Right, 10))

Output:

     lorem
     ipsum

func AlignCenter Uses

func AlignCenter(str string, width int) string

AlignCenter centers str. It trims and then centers all the lines in the text with space

Code:

text := AlignCenter("lorem\nipsum", 9)
fmt.Println(strings.Replace(text, " ", ".", -1))

Output:

..lorem..
..ipsum..

func AlignLeft Uses

func AlignLeft(str string) string

AlignLeft aligns string to the left. To achieve that it left trims every line.

Code:

fmt.Println(AlignLeft("   lorem\n    ipsum"))

Output:

lorem
ipsum

func AlignRight Uses

func AlignRight(str string, width int) string

AlignRight aligns string to the right. It trims and left pads all the lines in the text with space to the size of width.

Code:

fmt.Println(AlignRight("  lorem  \n  ipsum  ", 10))

Output:

     lorem
     ipsum

func CenterText Uses

func CenterText(str string, width int) string

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 Uses

func CountWords(str string) int

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

Code:

fmt.Println(CountWords("It is not known exactly!"))

Output:

5

func DrawBox Uses

func DrawBox(content string, width int, align AlignType) (string, error)

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    │
└──────────────────┘

Code:

output, _ := DrawBox("Hello World", 20, Center)
fmt.Println(output)

Output:

┌──────────────────┐
│   Hello World    │
└──────────────────┘

Code:

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 Uses

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    |
+------------------+

Code:

output, _ := DrawCustomBox("Hello World", 20, Center, DefaultBox9Slice(), "\n")
fmt.Println(output)

Output:

┌──────────────────┐
│   Hello World    │
└──────────────────┘

func ExpandTabs Uses

func ExpandTabs(str string, count int) string

ExpandTabs converts tabs to the spaces. count specifies the number of spaces

Code:

fmt.Printf("%s", ExpandTabs("\tlorem\n\tipsum", 2))

Output:

  lorem
  ipsum

func Indent Uses

func Indent(str string, left string) string

Indent indents every line of string str with the left parameter Empty lines are indented too.

Code:

fmt.Println(Indent("Lorem ipsum\ndolor sit amet", " > "))

Output:

 > Lorem ipsum
 > dolor sit amet

func IsASCII Uses

func IsASCII(s string) bool

IsASCII checks if all the characters in string are in standard ASCII table It is taken from strings.Fields function

func MapLines Uses

func MapLines(str string, fn func(string) string) string

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"

Code:

fmt.Println(MapLines("Lorem\nIpsum", strings.ToUpper))

Output:

LOREM
IPSUM

func MustSubstring Uses

func MustSubstring(str string, start int, end int) string

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.

Code:

fmt.Println(MustSubstring("Υπάρχουν", 1, 4))

Output:

πάρ

Code:

fmt.Println(MustSubstring("Υπάρχουν", 1, 0))

Output:

πάρχουν

func OSNewLine Uses

func OSNewLine() string

OSNewLine returns operating system's default new line character. It is \r\n in Windowns and \n elsewhere.

func Pad Uses

func Pad(str string, width int, leftPad string, rightPad string) string

Pad left and right pads a string str with leftPad and rightPad. The string is padded to the size of width.

Code:

fmt.Println(Pad("lorem", 9, "-", "-"))

Output:

--lorem--

func PadLeft Uses

func PadLeft(str string, width int, pad string) string

PadLeft left pads a string str with "pad". The string is padded to the size of width.

Code:

fmt.Println(PadLeft("lorem", 10, "-"))

Output:

-----lorem

func PadRight Uses

func PadRight(str string, width int, pad string) string

PadRight right pads a string str with "pad". The string is padded to the size of width.

Code:

fmt.Println(PadRight("lorem", 10, "-"))

Output:

lorem-----

func Random Uses

func Random(strSet string, length int) (string, error)

Random creates new string based on strSet. It uses crypto/rand as the random number generator. error is the one returned by rand.Int

Code:

fmt.Println(Random("abcdefghik", 5))

func RemoveAccents Uses

func RemoveAccents(str string) string

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.

Code:

output := RemoveAccents("ßąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșşšŝťțţŭùúüűûñÿýçżźž")
fmt.Println(output)

Output:

ssaaaaaaaaeaccceeeeeghiiiijllnnoooooodjoessssstttuuuuuunyyczzz

func ReplaceAllToOne Uses

func ReplaceAllToOne(str string, from []string, to string) string

ReplaceAllToOne replaces every string in the "from" with the string "to"

Code:

fmt.Println(ReplaceAllToOne("lorem", []string{"lo", "em"}, "x"))

Output:

xrx

func Reverse Uses

func Reverse(s string) string

Reverse reverses the string Copied from here https://stackoverflow.com/a/20225618/153570

Code:

fmt.Println(Reverse("επαγγελματίες"))

Output:

ςείταμλεγγαπε

func Slugify Uses

func Slugify(str string) string

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

Code:

fmt.Println(Slugify("We löve Motörhead"))

Output:

we-love-motorhead

func SlugifySpecial Uses

func SlugifySpecial(str string, delimiter string) string

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

Code:

fmt.Println(SlugifySpecial("We löve Motörhead", "_"))

Output:

we_love_motorhead

func Splice Uses

func Splice(str string, newStr string, start int, end int) string

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

Code:

fmt.Println(Splice("Lorem", "ipsum", 2, 3))

Output:

Loipsumem

func SplitAndMap Uses

func SplitAndMap(str string, split string, fn func(string) string) string

SplitAndMap splits the string and runs the function fn on every part

func SplitCamelCase Uses

func SplitCamelCase(str string) []string

SplitCamelCase splits and returns words in camelCase format.

Example:

SplitCamelCase("loremIpsum") //Output []string{"lorem", "Ipsum"}

Code:

fmt.Printf("%#v\n", SplitCamelCase("binaryJSONAbstractWriter"))

Output:

[]string{"binary", "JSON", "Abstract", "Writer"}

func Substring Uses

func Substring(str string, start int, end int) (string, error)

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 Uses

func Summary(str string, length int, end string) string

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

Code:

fmt.Println(Summary("Lorem ipsum dolor sit amet.", 12, "..."))

Output:

Lorem ipsum...

func Tile Uses

func Tile(pattern string, length int) string

Tile repeats the pattern until the result reaches the 'length' It returns empty string if the pattern is "" or length <= 0

func ToCamelCase Uses

func ToCamelCase(str string) string

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

Code:

fmt.Println(ToCamelCase("long live motörhead"))

Output:

longLiveMotörhead

func ToSnakeCase Uses

func ToSnakeCase(str string) string

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

Code:

fmt.Println(ToSnakeCase("Lorem Ipsum"))

Output:

lorem_ipsum

func WordWrap Uses

func WordWrap(str string, colLen int, breakLongWords bool) string

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.

Code:

fmt.Println(WordWrap("Lorem ipsum, dolor sit amet.", 15, false))

Output:

Lorem ipsum,
dolor sit amet.

func Words Uses

func Words(str string) []string

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: ', -, _

type AlignType Uses

type AlignType string

AlignType text align variable like center or left

const (
    Center AlignType = "center"
    Left   AlignType = "left"
    Right  AlignType = "right"
)

Align type to use with align function

type Box9Slice Uses

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 Uses

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 Uses

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    |
+------------------+

Package strutil imports 8 packages (graph). Updated 2019-10-13. Refresh now. Tools for package owners.