strutil

package module
Version: v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2021 License: MIT Imports: 8 Imported by: 0

README

String Utilities for Go

Tests GoReportCard GoDocs

"strutil" provides string functions for go applications.

For documentation with examples see GoDoc

Functions

Align (Docs)

Aligns the text to the specified side

strutil.Align("lorem ipsum", strutil.Right, 20) //->"        lorem ipsum" 
AlignCenter (Docs)

Aligns the text to the center

strutil.AlignCenter("lorem\nipsum", 10) //->"  lorem   \n  ipsum   " 
AlignLeft (Docs)

Aligns the text to the left

strutil.AlignLeft("  lorem   \n  ipsum   ") //->"lorem   \nipsum   " 
AlignRight (Docs)

Aligns the text to the right

strutil.AlignRight("lorem\nipsum", 10) //-> "     lorem\n     ipsum" 
CountWords (Docs)

Counts the words

strutil.CountWords("Lorem ipsum, dolor sit amet") //-> "5"
DrawBox (Docs)

Draws a frame around the string with default character set

strutil.DrawBox("Hello World", 20, strutil.Center)
//┌──────────────────┐
//│   Hello World    │
//└──────────────────┘
DrawCustomBox (Docs)

Draws a frame around the string with custom character set

strutil.DrawCustomBox("Hello World", 20, strutil.Center, strutil.SimpleBox9Slice(), "\n")
//┌──────────────────┐
//│   Hello World    │
//└──────────────────┘
ExpandTabs (Docs)

Converts tabs to the spaces

strutil.ExpandTabs("\tlorem\n\tipsum\n", 2) //-> "  lorem\n  ipsum\n"
Indent (Docs)

Indents every line

strutil.Indent("lorem\nipsum", "> ") //-> "> lorem\n> ipsum"
IsASCII (Docs)

Checks if all the characters in string are in standard ASCII table

strutil.IsASCII("lorem\nipsum") //-> true
Len (Docs)

Alias of utf8.RuneCountInString which returns the number of runes in string

strutil.Len("böt") //-> "3"
MapLines (Docs)

Runs function fn on every line of the string

strutil.MapLines("   lorem      \n    ipsum      ", strings.TrimSpace) //-> "lorem\nipsum"
OSNewLine (Docs)

OSNewLine returns operating systems default new line character

strutil.OSNewLine() //-> "\n"
Pad (Docs)

Left and right pads the string

strutil.Pad("lorem", 11, "->", "<-") //-> "->->lorem<-<-"
PadLeft (Docs)

Left pads the string

strutil.PadLeft("lorem", 9, "->") //-> "->->lorem"
PadRight (Docs)

Right pads the string

strutil.PadRight("lorem", 9, "<-") //-> "lorem<-<-"
Random (Docs)

Creates a random string from a character set

strutil.Random("abcdefghi", 10) //-> "aciafbeafg"
RemoveAccents (Docs)

Convert accented letters to ascii counterparts

strutil.RemoveAccents("résumé") //-> "resume"
ReplaceAllToOne (Docs)

Replace all substrings in the text with the specified string

strutil.ReplaceAllToOne("lorem ipsum", []string{"o","e","i","u"}, ".") //-> "l.r.m .ps.m"
Reverse (Docs)

Reverses the string

strutil.Reverse("lorem") //-> "merol"
Splice (Docs)

Replaces a part of the string

strutil.Splice("lorem", "-x-", 2, 3) //-> "lo-x-em"
SplitAndMap (Docs)

Splits the string and runs the function fn on every part

strutil.MapLines("lorem-ipsum-dolor", "-",  strutil.Reverse) //-> "merol\nmuspi\nrolod"
Slugify (Docs)

Converts the string to a slug

strutil.Slugify("Lorem ipsum, dolör") //-> "lorem-ipsum-dolor"
SlugifySpecial (Docs)

Converts the string to a slug with custom delimiter.

strutil.SlugifySpecial("Lorem ipsum, dolör", "_") //-> "lorem_ipsum_dolor"
SplitCamelCase (Docs)

Splits the words in a camelCase string

strutil.SplitCamelCase("loremIpsum") //-> []string{"lorem", "Ipsum"}
Substring (Docs)

Gets a part of the string without panics

strutil.SafeSubstring("lorem", 0, 1) //-> "l"
MustSubstring (Docs)

Gets a part of the string

strutil.Substring("lorem", 0, 1) //-> "l"
Summary (Docs)

Cuts the string to the specified length

strutil.Summary("Lorem ipsum dolor sit amet",  10, "...") //-> "lorem ipsum..."
Tile (Docs)

Repeats the pattern until the result reaches the 'length'

strutil.Tile("-৹", 4) //-> "-৹-৹"
ToSnakeCase (Docs)

Converts the string to snake_case

strutil.ToSnakeCase("Snake Case") //-> "snake_case"
ToCamelCase (Docs)

Converts the string to camelCase

strutil.ToCamelCase("Camel Case") //-> "camelCase"
Words (Docs)

Returns the words inside the text

strutil.Words("Lorem ipsum, dolor sit amet") //-> []string{"Lorem", "ipsum", "dolor", "sit", "amet"}
WordWrap (Docs)

Wraps the lines in the text

strutil.WordWrap("Lorem ipsum dolor sit amet", 15, false) //-> "Lorem ipsum\ndolor sit amet"

Install

Prequsities:

  • Go 1.10+

Install with

go get github.com/ozgio/strutil

Documentation

Overview

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

Index

Examples

Constants

This section is empty.

Variables

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

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

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

     lorem
     ipsum

func AlignCenter

func AlignCenter(str string, width int) string

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

func AlignLeft(str string) string

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

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.

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

     lorem
     ipsum

func CenterText added in v0.3.0

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

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

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

5

func DrawBox added in v0.3.0

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

func ExpandTabs(str string, count int) string

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

func Indent(str string, left string) string

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

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

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"

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

LOREM
IPSUM

func MustSubstring added in v0.3.0

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.

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

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.

Example
fmt.Println(Pad("lorem", 9, "-", "-"))
Output:

--lorem--

func PadLeft

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.

Example
fmt.Println(PadLeft("lorem", 10, "-"))
Output:

-----lorem

func PadRight

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.

Example
fmt.Println(PadRight("lorem", 10, "-"))
Output:

lorem-----

func Random added in v0.2.0

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

Example
fmt.Println(Random("abcdefghik", 5))
Output:

func RemoveAccents

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.

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

ssaaaaaaaaeaccceeeeeghiiiijllnnoooooodjoessssstttuuuuuunyyczzz

func ReplaceAllToOne

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

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

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

xrx

func Reverse

func Reverse(s string) string

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

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

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

func Slugify

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
Example
fmt.Println(Slugify("We löve Motörhead"))
Output:

we-love-motorhead

func SlugifySpecial

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
Example
fmt.Println(SlugifySpecial("We löve Motörhead", "_"))
Output:

we_love_motorhead

func Splice added in v0.2.0

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

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

Loipsumem

func SplitAndMap added in v0.3.0

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

func SplitCamelCase(str string) []string

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

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 added in v0.2.0

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

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

Lorem ipsum...

func Tile added in v0.3.0

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

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
Example
fmt.Println(ToCamelCase("long live motörhead"))
Output:

longLiveMotörhead

func ToSnakeCase

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
Example
fmt.Println(ToSnakeCase("Lorem Ipsum"))
Output:

lorem_ipsum

func WordWrap added in v0.3.0

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.

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

Lorem ipsum,
dolor sit amet.

func Words added in v0.2.0

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

Types

type AlignType added in v0.3.0

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

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL