diff --git a/changelog.md b/changelog.md index cfca3426..318b184a 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,9 @@ ## Changelog +#### v1.6.3 + +* `[strutil]` Added methods PrefixSize and SuffixSize + #### v1.6.2 * `[fsutil]` Improved working with paths diff --git a/strutil/strutil.go b/strutil/strutil.go index d79db1fc..c1ead208 100644 --- a/strutil/strutil.go +++ b/strutil/strutil.go @@ -110,3 +110,41 @@ func Tail(s string, n int) string { return s[l-n:] } + +// PrefixSize return prefix size +func PrefixSize(str string, prefix rune) int { + if str == "" { + return 0 + } + + var result int + + for i := 0; i < len(str); i++ { + if rune(str[i]) != prefix { + return result + } + + result++ + } + + return result +} + +// SuffixSize return suffix size +func SuffixSize(str string, suffix rune) int { + if str == "" { + return 0 + } + + var result int + + for i := len(str) - 1; i >= 0; i-- { + if rune(str[i]) != suffix { + return result + } + + result++ + } + + return result +} diff --git a/strutil/strutil_test.go b/strutil/strutil_test.go index 6368f7cf..bdc6fb0e 100644 --- a/strutil/strutil_test.go +++ b/strutil/strutil_test.go @@ -67,3 +67,15 @@ func (s *StrUtilSuite) TestTail(c *C) { c.Assert(Tail("ABCD1234", 4), Equals, "1234") c.Assert(Tail("ABCD1234", 100), Equals, "ABCD1234") } + +func (s *StrUtilSuite) TestSize(c *C) { + c.Assert(PrefixSize("", ' '), Equals, 0) + c.Assert(PrefixSize("abcd", ' '), Equals, 0) + c.Assert(PrefixSize(" abcd", ' '), Equals, 4) + c.Assert(PrefixSize(" ", ' '), Equals, 4) + + c.Assert(SuffixSize("", ' '), Equals, 0) + c.Assert(SuffixSize("abcd", ' '), Equals, 0) + c.Assert(SuffixSize("abcd ", ' '), Equals, 4) + c.Assert(SuffixSize(" ", ' '), Equals, 4) +}