diff --git a/docs/docs/strings.md b/docs/docs/strings.md index cddff2ac..9b4ada2d 100644 --- a/docs/docs/strings.md +++ b/docs/docs/strings.md @@ -296,4 +296,15 @@ Returns a boolean indicating that the given string is an lower case letter. "D".isLower(); // false "d".isLower() // true "Dog".isLower() // false -``` \ No newline at end of file +``` + +### string.wordCount() -> Number + +Returns the number of words in the given string. + +```cs +"".wordCount(); // 0 +"This".wordCount(); // 1 +"This is a sentence".wordCount(); // 4 +"This is an even longer sentence".wordCount(); // 6 +``` diff --git a/src/vm/datatypes/strings.c b/src/vm/datatypes/strings.c index f2453841..e3bafaee 100644 --- a/src/vm/datatypes/strings.c +++ b/src/vm/datatypes/strings.c @@ -545,6 +545,32 @@ static Value countString(DictuVM *vm, int argCount, Value *args) { return NUMBER_VAL(count); } +static Value wordCountString(DictuVM *vm, int argCount, Value *args) { + if (argCount != 0) { + runtimeError(vm, "count() takes no arguments (%d given)", argCount); + return EMPTY_VAL; + } + + char *string = AS_CSTRING(args[0]); + + int count = 0; + int len = strlen(string); + bool in = false; + + for (int i = 0; i < len; i++) { + if (isspace(string[i])) { + in = false; + } else if(isalpha(string[i])) { + if(!in) { + in = true; + count++; + } + } + } + + return NUMBER_VAL(count); +} + static Value titleString(DictuVM *vm, int argCount, Value *args) { if (argCount != 0) { runtimeError(vm, "title() takes no arguments (%d given)", argCount); @@ -657,6 +683,7 @@ void declareStringMethods(DictuVM *vm) { defineNative(vm, &vm->stringMethods, "rightStrip", rightStripString); defineNative(vm, &vm->stringMethods, "strip", stripString); defineNative(vm, &vm->stringMethods, "count", countString); + defineNative(vm, &vm->stringMethods, "wordCount", wordCountString); defineNative(vm, &vm->stringMethods, "toBool", boolNative); // Defined in util defineNative(vm, &vm->stringMethods, "title", titleString); defineNative(vm, &vm->stringMethods, "repeat", repeatString); diff --git a/tests/strings/import.du b/tests/strings/import.du index 045fc19a..709f74fe 100644 --- a/tests/strings/import.du +++ b/tests/strings/import.du @@ -28,3 +28,4 @@ import "repeat.du"; import "title.du"; import "isUpper.du"; import "isLower.du"; +import "wordCount.du"; diff --git a/tests/strings/wordCount.du b/tests/strings/wordCount.du new file mode 100644 index 00000000..6f93cfde --- /dev/null +++ b/tests/strings/wordCount.du @@ -0,0 +1,19 @@ +/** + * wordCount.du + * + * Testing the str.wordCount() method + * + * .wordCount() returns the number of words in the given string. + */ +from UnitTest import UnitTest; + +class TestStringWordCount < UnitTest { + testStringWordCount() { + this.assertEquals("".wordCount(), 0); + this.assertEquals("This".wordCount(), 1); + this.assertEquals("This is a sentence".wordCount(), 4); + this.assertEquals("This is an even longer sentence".wordCount(), 6); + } +} + +TestStringWordCount().run();