summaryrefslogtreecommitdiff
path: root/strings
diff options
context:
space:
mode:
Diffstat (limited to 'strings')
-rw-r--r--strings/strings.go20
-rw-r--r--strings/strings_test.go15
2 files changed, 35 insertions, 0 deletions
diff --git a/strings/strings.go b/strings/strings.go
index 269e760f..073375e7 100644
--- a/strings/strings.go
+++ b/strings/strings.go
@@ -2,6 +2,7 @@
package strings
import (
+ "fmt"
"regexp"
"sort"
"strings"
@@ -125,3 +126,22 @@ func WordWrap(in string, opts WordWrapOpts) string {
opts = wwDefaults(opts)
return goutils.WrapCustom(in, int(opts.Width), opts.LBSeq, false)
}
+
+// SkipLines - skip the given number of lines (ending with \n) from the string.
+// If skip is greater than the number of lines in the string, an empty string is
+// returned.
+func SkipLines(skip int, in string) (string, error) {
+ if skip < 0 {
+ return "", fmt.Errorf("skip must be >= 0")
+ }
+ if skip == 0 {
+ return in, nil
+ }
+
+ lines := strings.SplitN(in, "\n", skip+1)
+ if skip >= len(lines) {
+ return "", nil
+ }
+
+ return lines[skip], nil
+}
diff --git a/strings/strings_test.go b/strings/strings_test.go
index e79614f9..46ca6d86 100644
--- a/strings/strings_test.go
+++ b/strings/strings_test.go
@@ -126,3 +126,18 @@ that has been set.`
// in = strings.ReplaceAll(out, "\n", " ")
// assert.Equal(t, out, WordWrap(in, WordWrapOpts{Width: 100}))
}
+
+func TestSkipLines(t *testing.T) {
+ out, _ := SkipLines(2, "\nfoo\nbar\n\nbaz")
+ assert.Equal(t, "bar\n\nbaz", out)
+
+ out, _ = SkipLines(0, "foo\nbar\n\nbaz")
+ assert.Equal(t, "foo\nbar\n\nbaz", out)
+
+ _, err := SkipLines(-1, "foo\nbar\n\nbaz")
+ assert.Error(t, err)
+
+ out, err = SkipLines(4, "foo\nbar\n\nbaz")
+ assert.NoError(t, err)
+ assert.Equal(t, "", out)
+}