Merge pull request #6 from AkselMeola/feature/5-prefix-suffix

Add methods for prefixing and suffixing
This commit is contained in:
Roshan Ranabhat 2021-05-14 21:40:27 +05:45 committed by GitHub
commit 089d9d1aa9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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
``` bash

View File

@ -74,4 +74,9 @@ func main() {
last := lcn.Last(4)
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
ToUpper() string
UcFirst() string
Prefix(with string) string
Suffix(with string) string
}
// New func returns pointer to input struct
@ -329,3 +331,23 @@ func (i *input) UcFirst() string {
input := getInput(*i)
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
import (
"fmt"
"testing"
)
@ -310,3 +311,29 @@ func TestInput_Last(t *testing.T) {
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/
// _
}