changeset 152:a6739206a9e3

Add splitOn and partitionOn to string objects
author Mike Pavone <pavone@retrodev.com>
date Fri, 09 Aug 2013 20:12:04 -0700
parents 3e9cb69e516d
children 075b1e71feff
files modules/string.tp samples/stringops.tp
diffstat 2 files changed, 39 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/modules/string.tp	Fri Aug 09 13:20:40 2013 -0700
+++ b/modules/string.tp	Fri Aug 09 20:12:04 2013 -0700
@@ -151,5 +151,36 @@
 		from: start withLength: length
 	}
 
+	partitionOn <- :delim {
+		pos <- find: delim else: { -1 }
+		if: pos >= 0 {
+			_before <- from: 0 withLength: pos
+			_after <- from: (pos + (delim length))
+			#{
+				before <- _before
+				after <- _after
+			}
+		} else: {
+			_before <- self
+			#{
+				before <- _before
+				after <- ""
+			}
+		}
+	}
+
+	splitOn <- :delim {
+		pos <- 0
+		pieces <- #[]
+		while: {
+			pos <- find: delim else: { -1 }
+			pos >= 0
+		} do: {
+			pieces append: (from: 0 withLength: pos)
+			self <- from: pos + (delim length)
+		}
+		pieces append: self
+	}
+
 	isInteger? <- { false }
 }
--- a/samples/stringops.tp	Fri Aug 09 13:20:40 2013 -0700
+++ b/samples/stringops.tp	Fri Aug 09 20:12:04 2013 -0700
@@ -9,5 +9,13 @@
 
 		print: ("foobarbaz" from: 3) . "\n"
 		print: ("foobarbaz" from: 3 withLength: 3) . "\n"
+
+		foreach: ("foo,bar,baz,qux" splitOn: ",") :idx val {
+			print: val . "\n"
+		}
+
+		res <- "foobarbaz" partitionOn: "bar"
+		print: "Before: " . (res before) . "\n"
+		print: "After: " . (res after) . "\n"
 	}
 }