Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions cstring.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleting the first element takes O(n), it's too much
It'll be better just set some sort of start_position to 1 and then start loop not from 0 but from start_position

}
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');
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Else (when it's not a digit) set error like "Not a Number" using setError()

About error handling here

}
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;
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also setError()

}
}
return sign * result;
}

TString stringInit(size_t capacity) {
TString s = {0};
s.data = (char *) malloc(sizeof(char) * capacity);
Expand Down
16 changes: 16 additions & 0 deletions tests/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add test with empty string or invalid double -12pas7 8.14

P.S. you forgot to call this test in main()

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;
}
Expand Down