strutil

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2018 License: MIT Imports: 10 Imported by: 15

README

String Utilities for Go

CircleCI cover.run GoReportCard GoDocs

"strutil" provides string functions for go applications.

In some functions it may not work as expected in non-latin alphabets like cyrillic, chinese, etc. Also there may be some language spesific edge cases that aren't supported well. Any help on those areas would be appreciated.

For documentation with examples see GoDoc

Functions

Function Desctiption
Align Aligns the text to the spesified side
AlignCenter Aligns the text to the center
AlignLeft Aligns the text to the left
AlignRight Aligns the text to the right
Box Draws a frame around the string with default chars
Center Centers the string
CountWords Count the words in the string
CustomBox Draws a frame aroud the string with specified chars
ExpandTabs Converts tabs to spaces
Indent Indents the string
MapLines Runs spesified function on every line of the text
Pad Left and right pads the strings
PadLeft Left pads the string
PadRight Right pads the string
Random Creates a random string from a character set
RemoveAccents Remove accents in the string
ReplaceAllToOne Replace all substrings in the text to the spesified string
Reverse Reverses the string
Slugify Converts the string to a slug
SplitCamelCase Splits the words in a camelCase string
ToCamelCase Converts the string to camelCase
ToSnakeCase Converts the string to snake_Case
Substring Returns a part of the string
Summary Cuts the text to the length
Splice Replaces a part of the string
Wordwrap Wraps the lines in the text

Install

Prequsities:

  • Go 1.10+

Install with

go get github.com/ozgio/strutil

Dependencies:

go get golang.org/x/text/runes
go get golang.org/x/text/transform
go get golang.org/x/text/unicode/norm

Import

import "github.com/ozgio/strutil"

TODO

  • Improve tests. More test cases are needed
  • Test for different languages
  • Handle "\r\n"
  • Improve whitespace and punctiation support

Documentation

Overview

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

Index

Examples

Constants

View Source
const (
	AlignTypeCenter = "center"
	AlignTypeLeft   = "left"
	AlignTypeRight  = "right"
)

Align type to use with align function

Variables

View Source
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 "İ"

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

func Align(str string, typ string, width int) string

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

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, width int) string

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

func AlignRight(str string, width int) string

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

func Box(content string, width int, align string) (string, error)

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

func Center(str string, width int) string

Center centers the text by adding spaces to the left and right.

Example
fmt.Println("'" + Center("lorem", 9) + "'")
Output:

'  lorem  '

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 CustomBox

func CustomBox(content string, width int, align string, chars Box9Slice) (string, error)

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

func ExpandTabs(str string, count int) string

ExpandTabs convert tabs the spaces with the length of count

func Indent

func Indent(str string, left string) string

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

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 "\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

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

func RemoveAccents

func RemoveAccents(str string) (string, int, error)

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

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

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

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

xrx

func Reverse

func Reverse(str string) string

Reverse reverses the string

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

we-love-motorhead

func SlugifySpecial

func SlugifySpecial(str string, delimeter string) string

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

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

func SplitCamelCase(str string) []string

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

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

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

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 break up the words by spaces

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

Lorem ipsum...

func ToCamelCase

func ToCamelCase(str string) string

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

func ToSnakeCase(str string) string

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

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

func Wordwrap

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.

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

Jump to

Keyboard shortcuts

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