Преглед на файлове

Merge pull request #214 from hallzy/split_emtpy_arg

split('') will now split a string at every character.
Marco Bambini преди 7 години
родител
ревизия
c08e8b59cb
променени са 3 файла, в които са добавени 35 реда и са изтрити 2 реда
  1. 6 0
      docs/types.html
  2. 12 2
      src/runtime/gravity_core.c
  3. 17 0
      test/unittest/string/split_string_to_list.gravity

+ 6 - 0
docs/types.html

@@ -137,6 +137,12 @@
 	list[0]                // "Roses are Red"
 	list[1]                // "Violets are Blue"
 
+	// Split can also be used to convert a string to a list type so that you can
+	// call list specific methods
+	var string = "abcdefghijklmnpqrstuvwxyz".split('')
+	string.contains("o")   // false
+	string.contains("s")   // true
+
 	// You are also able to edit strings by character...
 	b[0] = "Z"              // b is now "Zello World"
 	b[1] = "abc"            // b is now "Zabco World"

+ 12 - 2
src/runtime/gravity_core.c

@@ -2228,9 +2228,19 @@ static bool string_split (gravity_vm *vm, gravity_value_t *args, uint16_t nargs,
 	// initialize the list to have a size of 0
 	gravity_list_t *list = gravity_list_new(vm, 0);
 
-	// split loop
 	char *original = string->s;
-    uint32_t slen = string->len;
+	uint32_t slen = string->len;
+
+	// If the separator is empty, then we split the string at every character
+	if (seplen == 0) {
+    for (uint32_t i=0; i<slen; ++i) {
+			marray_push(gravity_value_t, list->array, VALUE_FROM_STRING(vm, original, 1));
+			original += 1;
+		}
+		RETURN_VALUE(VALUE_FROM_OBJECT(list), rindex);
+	}
+
+	// split loop
 	while (1) {
 		char *p = string_strnstr(original, sep, (size_t)slen);
 		if (p == NULL) {

+ 17 - 0
test/unittest/string/split_string_to_list.gravity

@@ -0,0 +1,17 @@
+#unittest {
+	name: "Split() with empty argument Test";
+	error: NONE;
+	result: true;
+};
+
+func main () {
+	var s = "123456789"
+  var list = s.split("")
+
+	var sum = list.reduce(0, func(num1, num2) {
+		return num1.Int()+num2.Int()
+	})
+
+	// Check expected just to make sure the loop actually ran
+	return sum == 45 and list.count == 9
+}