Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add count-substrings

  • Loading branch information...
commit 04f4adcb85303430816881a4a98f00d7c91b699a 1 parent 3a11c7b
@cgay authored
View
1  library.dylan
@@ -67,6 +67,7 @@ define module strings
find-substring,
replace-substrings,
+ count-substrings,
// skip-whitespace -- position-if(whitespace?, <sequence>)
// override find(...) in common-extensions
View
31 substring-search.dylan
@@ -63,6 +63,37 @@ define sealed inline method find-substring
compiled-pattern)
end method find-substring;
+
+define generic count-substrings
+ (big :: <string>, pattern :: <string>, #key start, end: epos, ignore-case?)
+ => (count :: <integer>);
+
+define method count-substrings
+ (big :: <string>, pattern :: <string>,
+ #key start :: <integer> = 0,
+ end: epos :: <integer> = big.size,
+ ignore-case? :: <boolean>)
+ => (count :: <integer>)
+ let patlen = pattern.size;
+ if (patlen == 0)
+ big.size + 1
+ else
+ iterate loop (bpos = start, count = 0)
+ if (bpos < epos)
+ let index = find-substring(big, pattern,
+ start: bpos, end: epos, ignore-case?: ignore-case?);
+ format-out("index = %s\n", index);
+ xif(index,
+ loop(index + patlen, count + 1),
+ count)
+ else
+ count
+ end
+ end
+ end
+end method count-substrings;
+
+
define sealed method make-substring-positioner
(pattern :: <byte-string>, case-sensitive :: <boolean>)
=> (positioner :: <function>)
View
23 tests/strings-test-suite.dylan
@@ -85,6 +85,9 @@ define module-spec strings ()
sealed generic-function replace-substrings
(<string>, <string>, <string>, #"key", #"start", #"end", #"count", #"ignore-case?")
=> (<string>);
+ sealed generic-function count-substrings
+ (<string>, <string>, #"key", #"start", #"end", #"ignore-case?")
+ => (<integer>);
function split-lines (<string>, #"key", #"remove-if-empty?") => (<sequence>);
end module-spec strings;
@@ -282,13 +285,9 @@ end function-test printable?;
////
-//// Slices / substrings
+//// Substrings
////
-define strings function-test slice ()
- //---*** Fill this in...
-end function-test slice;
-
define strings function-test find-substring ()
//---*** Fill this in...
end function-test find-substring;
@@ -303,6 +302,20 @@ define strings function-test replace-substrings ()
check-equal("end", replace-substrings("zig zig", "zi", "pi", end: 5), "pig zig");
end function-test replace-substrings;
+define strings function-test count-substrings ()
+ let data = #(#(1, "", ""),
+ #(2, "x", ""),
+ #(1, "x", "x"),
+ #(2, "xxxxx", "xx"), // check non-overlap
+ #(1, "xxxxx", "xx", start:, 1, end:, 4),
+ #(0, "xxx", "X"),
+ #(3, "xxx", "X", ignore-case?:, #t));
+ for (item in data)
+ let (expected, #rest args) = apply(values, item);
+ check-equal(fmt("%s", args), apply(count-substrings, args), expected);
+ end;
+end function-test count-substrings;
+
////
//// Digits
Please sign in to comment.
Something went wrong with that request. Please try again.