diff --git a/cstring.h b/cstring.h index ba1bf2d..5108e03 100644 --- a/cstring.h +++ b/cstring.h @@ -363,6 +363,40 @@ int64_t stringFindFirstCharArr(TString s, const char *pattern) { return -1; } +double stringToDouble(TString s) { + double result = 0.0; + int sign = 1; + int decimalIndex = -1; + if (s.size > 0 && s.data[0] == '-') { + sign = -1; + stringRemove(&s, 0, 1); + } + for (size_t i = 0; i < s.size; ++i) { + if (s.data[i] == '.') { + decimalIndex = i; + break; + } + } + for (size_t i = 0; i < s.size; ++i) { + if (s.data[i] == '.') { + break; + } + if (stringCharIsDigit(s.data[i])) { + result = result * 10.0 + (s.data[i] - '0'); + } + } + double divisor = 10.0; + if (decimalIndex != -1) { + for (size_t i = decimalIndex + 1; i < s.size; ++i) { + if (stringCharIsDigit(s.data[i])) { + result += (s.data[i] - '0') / divisor; + divisor *= 10.0; + } + } + } + return sign * result; +} + TString stringInit(size_t capacity) { TString s = {0}; s.data = (char *) malloc(sizeof(char) * capacity); diff --git a/tests/main.c b/tests/main.c index fe2513c..0cd6944 100644 --- a/tests/main.c +++ b/tests/main.c @@ -372,6 +372,22 @@ void test_stringContains() { printGreen("test_stringContains\n"); } +void test_stringToDouble() { + TString s1 = stringInitWithCharArr("3.14159"); + TString s2 = stringInitWithCharArr("123"); + TString s3 = stringInitWithCharArr("-100"); + + assertEq(stringToDouble(s1), 3.14159); + assertEq(stringToDouble(s2), 123); + assertEq(stringToDouble(s3), -100); + + stringDestroy(&s1); + stringDestroy(&s2); + stringDestroy(&s3); + + printGreen("test_stringToDouble\n"); +} + bool acceptAll(char c) { return true; }