xstrings: github.com/huandu/xstrings Index | Files

package xstrings

import "github.com/huandu/xstrings"

Package xstrings is to provide string algorithms which are useful but not included in `strings` package. See project home page for details. https://github.com/huandu/xstrings

Package xstrings assumes all strings are encoded in utf8.

Index

Package Files

common.go convert.go count.go doc.go format.go manipulate.go translate.go

func Center Uses

func Center(str string, length int, pad string) string

Center returns a string with pad string at both side if str's rune length is smaller than length. If str's rune length is larger than length, str itself will be returned.

If pad is an empty string, str will be returned.

Samples:

Center("hello", 4, " ")    => "hello"
Center("hello", 10, " ")   => "  hello   "
Center("hello", 10, "123") => "12hello123"

func Count Uses

func Count(str, pattern string) int

Count how many runes in str match the pattern. Pattern is defined in Translate function.

Samples:

Count("hello", "aeiou") => 3
Count("hello", "a-k")   => 3
Count("hello", "^a-k")  => 2

func Delete Uses

func Delete(str, pattern string) string

Delete runes in str matching the pattern. Pattern is defined in Translate function.

Samples:

Delete("hello", "aeiou") => "hll"
Delete("hello", "a-k")   => "llo"
Delete("hello", "^a-k")  => "he"

func ExpandTabs Uses

func ExpandTabs(str string, tabSize int) string

ExpandTabs can expand tabs ('\t') rune in str to one or more spaces dpending on current column and tabSize. The column number is reset to zero after each newline ('\n') occurring in the str.

ExpandTabs uses RuneWidth to decide rune's width. For example, CJK characters will be treated as two characters.

If tabSize <= 0, ExpandTabs panics with error.

Samples:

ExpandTabs("a\tbc\tdef\tghij\tk", 4) => "a   bc  def ghij    k"
ExpandTabs("abcdefg\thij\nk\tl", 4)  => "abcdefg hij\nk   l"
ExpandTabs("z中\t文\tw", 4)           => "z中 文  w"

func FirstRuneToLower Uses

func FirstRuneToLower(str string) string

FirstRuneToLower converts first rune to lower case if necessary.

func FirstRuneToUpper Uses

func FirstRuneToUpper(str string) string

FirstRuneToUpper converts first rune to upper case if necessary.

func Insert Uses

func Insert(dst, src string, index int) string

Insert src into dst at given rune index. Index is counted by runes instead of bytes.

If index is out of range of dst, panic with out of range.

func LastPartition Uses

func LastPartition(str, sep string) (head, match, tail string)

LastPartition splits a string by last instance of sep into three parts. The return value is a slice of strings with head, match and tail.

If str contains sep, for example "hello" and "l", LastPartition returns

"hel", "l", "o"

If str doesn't contain sep, for example "hello" and "x", LastPartition returns

"", "", "hello"

func LeftJustify Uses

func LeftJustify(str string, length int, pad string) string

LeftJustify returns a string with pad string at right side if str's rune length is smaller than length. If str's rune length is larger than length, str itself will be returned.

If pad is an empty string, str will be returned.

Samples:

LeftJustify("hello", 4, " ")    => "hello"
LeftJustify("hello", 10, " ")   => "hello     "
LeftJustify("hello", 10, "123") => "hello12312"

func Len Uses

func Len(str string) int

Len returns str's utf8 rune length.

func Partition Uses

func Partition(str, sep string) (head, match, tail string)

Partition splits a string by sep into three parts. The return value is a slice of strings with head, match and tail.

If str contains sep, for example "hello" and "l", Partition returns

"he", "l", "lo"

If str doesn't contain sep, for example "hello" and "x", Partition returns

"hello", "", ""

func Reverse Uses

func Reverse(str string) string

Reverse a utf8 encoded string.

func RightJustify Uses

func RightJustify(str string, length int, pad string) string

RightJustify returns a string with pad string at left side if str's rune length is smaller than length. If str's rune length is larger than length, str itself will be returned.

If pad is an empty string, str will be returned.

Samples:

RightJustify("hello", 4, " ")    => "hello"
RightJustify("hello", 10, " ")   => "     hello"
RightJustify("hello", 10, "123") => "12312hello"

func RuneWidth Uses

func RuneWidth(r rune) int

RuneWidth returns character width in monotype font. Multi-byte characters are usually twice the width of single byte characters.

Algorithm comes from `mb_strwidth` in PHP. http://php.net/manual/en/function.mb-strwidth.php

func Scrub Uses

func Scrub(str, repl string) string

Scrub scrubs invalid utf8 bytes with repl string. Adjacent invalid bytes are replaced only once.

func Shuffle Uses

func Shuffle(str string) string

Shuffle randomizes runes in a string and returns the result. It uses default random source in `math/rand`.

func ShuffleSource Uses

func ShuffleSource(str string, src rand.Source) string

ShuffleSource randomizes runes in a string with given random source.

func Slice Uses

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

Slice a string by rune.

Start must satisfy 0 <= start <= rune length.

End can be positive, zero or negative. If end >= 0, start and end must satisfy start <= end <= rune length. If end < 0, it means slice to the end of string.

Otherwise, Slice will panic as out of range.

func Squeeze Uses

func Squeeze(str, pattern string) string

Squeeze deletes adjacent repeated runes in str. If pattern is not empty, only runes matching the pattern will be squeezed.

Samples:

Squeeze("hello", "")             => "helo"
Squeeze("hello", "m-z")          => "hello"
Squeeze("hello   world", " ")    => "hello world"

func Successor Uses

func Successor(str string) string

Successor returns the successor to string.

If there is one alphanumeric rune is found in string, increase the rune by 1. If increment generates a "carry", the rune to the left of it is incremented. This process repeats until there is no carry, adding an additional rune if necessary.

If there is no alphanumeric rune, the rightmost rune will be increased by 1 regardless whether the result is a valid rune or not.

Only following characters are alphanumeric.

* a - z
* A - Z
* 0 - 9

Samples (borrowed from ruby's String#succ document):

"abcd"      => "abce"
"THX1138"   => "THX1139"
"<<koala>>" => "<<koalb>>"
"1999zzz"   => "2000aaa"
"ZZZ9999"   => "AAAA0000"
"***"       => "**+"

func SwapCase Uses

func SwapCase(str string) string

SwapCase will swap characters case from upper to lower or lower to upper.

func ToCamelCase Uses

func ToCamelCase(str string) string

ToCamelCase can convert all lower case characters behind underscores to upper case character. Underscore character will be removed in result except following cases.

* More than 1 underscore.
      "a__b" => "A_B"
* At the beginning of string.
      "_a" => "_A"
* At the end of string.
      "ab_" => "Ab_"

func ToSnakeCase Uses

func ToSnakeCase(str string) string

ToSnakeCase can convert all upper case characters in a string to underscore format.

Some samples.

"FirstName"  => "first_name"
"HTTPServer" => "http_server"
"NoHTTPS"    => "no_https"
"GO_PATH"    => "go_path"
"GO PATH"    => "go_path"      // space is converted to underscore.
"GO-PATH"    => "go_path"      // hyphen is converted to underscore.

func Translate Uses

func Translate(str, from, to string) string

Translate str with the characters defined in from replaced by characters defined in to.

From and to are patterns representing a set of characters. Pattern is defined as following.

* Special characters
  * '-' means a range of runes, e.g.
    * "a-z" means all characters from 'a' to 'z' inclusive;
    * "z-a" means all characters from 'z' to 'a' inclusive.
  * '^' as first character means a set of all runes excepted listed, e.g.
    * "^a-z" means all characters except 'a' to 'z' inclusive.
  * '\' escapes special characters.
* Normal character represents itself, e.g. "abc" is a set including 'a', 'b' and 'c'.

Translate will try to find a 1:1 mapping from from to to. If to is smaller than from, last rune in to will be used to map "out of range" characters in from.

Note that '^' only works in the from pattern. It will be considered as a normal character in the to pattern.

If the to pattern is an empty string, Translate works exactly the same as Delete.

Samples:

Translate("hello", "aeiou", "12345")    => "h2ll4"
Translate("hello", "a-z", "A-Z")        => "HELLO"
Translate("hello", "z-a", "a-z")        => "svool"
Translate("hello", "aeiou", "*")        => "h*ll*"
Translate("hello", "^l", "*")           => "**ll*"
Translate("hello ^ world", `\^lo`, "*") => "he*** * w*r*d"

func Width Uses

func Width(str string) int

Width returns string width in monotype font. Multi-byte characters are usually twice the width of single byte characters.

Algorithm comes from `mb_strwidth` in PHP. http://php.net/manual/en/function.mb-strwidth.php

func WordCount Uses

func WordCount(str string) int

WordCount returns number of words in a string.

Word is defined as a locale dependent string containing alphabetic characters, which may also contain but not start with `'` and `-` characters.

func WordSplit Uses

func WordSplit(str string) []string

WordSplit splits a string into words. Returns a slice of words. If there is no word in a string, return nil.

Word is defined as a locale dependent string containing alphabetic characters, which may also contain but not start with `'` and `-` characters.

type Translator Uses

type Translator struct {
    // contains filtered or unexported fields
}

Translator can translate string with pre-compiled from and to patterns. If a from/to pattern pair needs to be used more than once, it's recommended to create a Translator and reuse it.

func NewTranslator Uses

func NewTranslator(from, to string) *Translator

NewTranslator creates new Translator through a from/to pattern pair.

func (*Translator) HasPattern Uses

func (tr *Translator) HasPattern() bool

HasPattern returns true if Translator has one pattern at least.

func (*Translator) Translate Uses

func (tr *Translator) Translate(str string) string

Translate str with a from/to pattern pair.

See comment in Translate function for usage and samples.

func (*Translator) TranslateRune Uses

func (tr *Translator) TranslateRune(r rune) (result rune, translated bool)

TranslateRune return translated rune and true if r matches the from pattern. If r doesn't match the pattern, original r is returned and translated is false.

Package xstrings imports 5 packages (graph) and is imported by 17 packages. Updated 2018-06-18. Refresh now. Tools for package owners.