Add methods for prefixing and suffixing

Closes #5

Add methods for prefixing and suffixing

Closes #5
This commit is contained in:
Aksel Meola 2021-05-14 13:41:41 +03:00
parent 299c6e83c4
commit b092f52a1b
4 changed files with 74 additions and 0 deletions

View File

@ -332,6 +332,26 @@ LcFirst simply returns result by lower casing first letter of string and it can
``` ```
#### Prefix(string) string
Prefix makes sure string has been prefixed with a given string and avoids adding it again if it has.
```go
ufo := stringy.New("known flying object")
fmt.Println(ufo.Prefix("un")) // unknown flying object
```
#### Suffix(string) string
Suffix makes sure string has been suffixed with a given string and avoids adding it again if it has.
```go
pun := stringy.New("this really is a cliff")
fmt.Println(pun.Suffix("hanger")) // this really is a cliffhanger
```
## Running the tests ## Running the tests
``` bash ``` bash

View File

@ -74,4 +74,9 @@ func main() {
last := lcn.Last(4) last := lcn.Last(4)
fmt.Println(last) // 1348 fmt.Println(last) // 1348
ufo := stringy.New("known flying object")
fmt.Println(ufo.Prefix("un")) // unknown flying object
pun := stringy.New("this really is a cliff")
fmt.Println(pun.Suffix("hanger")) // this really is a cliffhanger
} }

View File

@ -41,6 +41,8 @@ type StringManipulation interface {
ToLower() string ToLower() string
ToUpper() string ToUpper() string
UcFirst() string UcFirst() string
Prefix(with string) string
Suffix(with string) string
} }
// New func returns pointer to input struct // New func returns pointer to input struct
@ -329,3 +331,23 @@ func (i *input) UcFirst() string {
input := getInput(*i) input := getInput(*i)
return ucfirst(input) return ucfirst(input)
} }
// Prefix makes sure that string is prefixed with a given string
func (i *input) Prefix(with string) string {
input := getInput(*i)
if strings.HasPrefix(input, with) {
return input
}
return with + input
}
// Suffix makes sure that string is suffixed with a given string
func (i *input) Suffix(with string) string {
input := getInput(*i)
if strings.HasSuffix(input, with) {
return input
}
return input + with
}

View File

@ -1,6 +1,7 @@
package stringy package stringy
import ( import (
"fmt"
"testing" "testing"
) )
@ -310,3 +311,29 @@ func TestInput_Last(t *testing.T) {
t.Errorf("Expected: to be %s but got: %s", against, last) t.Errorf("Expected: to be %s but got: %s", against, last)
} }
} }
func ExampleStringManipulation_Prefix() {
fmt.Println(New("foobar").Prefix("foo"))
fmt.Println(New("foobar").Prefix("foofoo"))
fmt.Println(New("foobar").Prefix("/"))
fmt.Println(New("").Prefix("_"))
// Output:
// foobar
// foofoofoobar
// /foobar
// _
}
func ExampleStringManipulation_Suffix() {
fmt.Println(New("foobar").Suffix("bar"))
fmt.Println(New("foobar").Suffix("barbar"))
fmt.Println(New("foobar").Suffix("/"))
fmt.Println(New("foobar/").Suffix("/"))
fmt.Println(New("").Suffix("_"))
// Output:
// foobar
// foobarbarbar
// foobar/
// foobar/
// _
}