shithub: mc

Download patch

ref: ac2b69008a453fb8da4116636da2587ceb03db63
parent: 746a147dbd5a08af94388941ee11c87a33f15cb4
author: Ori Bernstein <[email protected]>
date: Mon Dec 16 13:28:14 EST 2013

Make strsplit() use strfind()

    This allows us to use any string as a delimiter.

--- a/libstd/strsplit.myr
+++ b/libstd/strsplit.myr
@@ -2,7 +2,9 @@
 use "die.use"
 use "extremum.use"
 use "fmt.use"
+use "option.use"
 use "slpush.use"
+use "strfind.use"
 use "sys.use"
 use "types.use"
 
@@ -11,20 +13,22 @@
 ;;
 
 const strsplit = {s, delim
-	var i
 	var last
 	var sp
 
 	sp = [][:]
 	last = 0
-	assert(delim.len == 1, "FIXME: We should support strings as delimiters")
-	for i = 0; i < s.len; i++
-		if s[i] == delim[0]
-			sp = slpush(sp, s[last:i])
-			last = i + 1
+	while true
+		match strfind(s, delim)
+		| `Some i:
+			sp = slpush(sp, s[:i])
+			s = s[i + delim.len:]
+		| `None:
+			goto donesplit
 		;;
 	;;
-	sp = slpush(sp, s[last:i])
+:donesplit
+	sp = slpush(sp, s[:])
 	-> sp
 }
 
--- a/test/data/strfind-expected
+++ b/test/data/strfind-expected
@@ -1,4 +1,6 @@
 No match
+No match
+No match
 Found 0
 Found 0
 No match
--- a/test/data/strsplit-expected
+++ b/test/data/strsplit-expected
@@ -1,4 +1,13 @@
-a
-b
-c
-d
+"a"
+"b"
+"c"
+"d"
+"a"
+""
+"b"
+"c"
+""
+"d"
+"a--b"
+"b--c"
+"c-d--d"
--- a/test/strsplit.myr
+++ b/test/strsplit.myr
@@ -6,6 +6,16 @@
 
 	sp = std.strsplit("a,b,c,d", ",")
 	for i = 0; i < sp.len; i++
-		std.put("%s\n", sp[i])
+		std.put("\"%s\"\n", sp[i])
+	;;
+
+	sp = std.strsplit("a,,b,c,,d", ",")
+	for i = 0; i < sp.len; i++
+		std.put("\"%s\"\n", sp[i])
+	;;
+
+	sp = std.strsplit("a--b---b--c---c-d--d", "---")
+	for i = 0; i < sp.len; i++
+		std.put("\"%s\"\n", sp[i])
 	;;
 }