mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Wrap and Unwrap func
This commit is contained in:
@@ -205,3 +205,34 @@ func ReverseStr(s string) string {
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
|
||||
// Wrap a string with another string.
|
||||
func Wrap(str string, wrapWith string) string {
|
||||
if str == "" || wrapWith == "" {
|
||||
return str
|
||||
}
|
||||
var sb strings.Builder
|
||||
sb.WriteString(wrapWith)
|
||||
sb.WriteString(str)
|
||||
sb.WriteString(wrapWith)
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// Unwrap a given string from anther string. will change str value
|
||||
func Unwrap(str string, wrapToken string) string {
|
||||
if str == "" || wrapToken == "" {
|
||||
return str
|
||||
}
|
||||
|
||||
firstIndex := strings.Index(str, wrapToken)
|
||||
lastIndex := strings.LastIndex(str, wrapToken)
|
||||
|
||||
if firstIndex == 0 && lastIndex > 0 && lastIndex <= len(str)-1 {
|
||||
if len(wrapToken) <= lastIndex {
|
||||
str = str[len(wrapToken):lastIndex]
|
||||
}
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
@@ -187,9 +187,6 @@ func isString(t *testing.T, test interface{}, expected bool) {
|
||||
func TestReverseStr(t *testing.T) {
|
||||
reverseStr(t, "abc", "cba")
|
||||
reverseStr(t, "12345", "54321")
|
||||
|
||||
//failed
|
||||
//reverseStr(t, "abc", "abc")
|
||||
}
|
||||
|
||||
func reverseStr(t *testing.T, test string, expected string) {
|
||||
@@ -199,3 +196,42 @@ func reverseStr(t *testing.T, test string, expected string) {
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
wrap(t, "ab", "", "ab")
|
||||
wrap(t, "", "*", "")
|
||||
wrap(t, "ab", "*", "*ab*")
|
||||
wrap(t, "ab", "\"", "\"ab\"")
|
||||
wrap(t, "ab", "'", "'ab'")
|
||||
}
|
||||
|
||||
func wrap(t *testing.T, test string, wrapWith string, expected string) {
|
||||
res := Wrap(test, wrapWith)
|
||||
if res != expected {
|
||||
internal.LogFailedTestInfo(t, "Wrap", test, expected, res)
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnwrap(t *testing.T) {
|
||||
unwrap(t, "", "*", "")
|
||||
unwrap(t, "ab", "", "ab")
|
||||
unwrap(t, "ab", "*", "ab")
|
||||
unwrap(t, "**ab**", "*", "*ab*")
|
||||
unwrap(t, "**ab**", "**", "ab")
|
||||
unwrap(t, "\"ab\"", "\"", "ab")
|
||||
unwrap(t, "*ab", "*", "*ab")
|
||||
unwrap(t, "ab*", "*", "ab*")
|
||||
unwrap(t, "***", "*", "*")
|
||||
unwrap(t, "**", "*", "")
|
||||
unwrap(t, "***", "**", "***")
|
||||
unwrap(t, "**", "**", "**")
|
||||
}
|
||||
|
||||
func unwrap(t *testing.T, test string, wrapToken string, expected string) {
|
||||
res := Unwrap(test, wrapToken)
|
||||
if res != expected {
|
||||
internal.LogFailedTestInfo(t, "Unwrap", test+"->"+wrapToken, expected, res)
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user