String Calculator
Level: IntermediateConcepts: Strings
Create a simple String calculator with a method that takes a string of numbers and returns their sum.
Requirements
- The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0).
- Allow the Add method to handle an unknown amount of numbers.
- Allow the Add method to handle new lines between numbers (instead of commas).
- Support different delimiters by starting the string with "//[delimiter]\n[numbers...]".
- Calling Add with a negative number will throw an exception "negatives not allowed" - and the negative that was passed.
- Numbers bigger than 1000 should be ignored.
- Delimiters can be of any length with the following format: "//[delimiter]\n".
- Allow multiple delimiters like this: "//[delim1][delim2]\n".
- Make sure you can also handle multiple delimiters with length longer than one char.
Test Cases
Input | Result | Notes |
---|---|---|
"" | 0 | Empty string returns 0 |
"1" | 1 | Single number returns itself |
"1,2" | 3 | Two numbers separated by comma |
"1,2,3" | 6 | Multiple numbers separated by comma |
"1\n2,3" | 6 | New line as delimiter |
"//;\n1;2" | 3 | Custom delimiter |
"-1,2" | Exception: "negatives not allowed: -1" | Negative numbers not allowed |
"2,1001" | 2 | Numbers > 1000 are ignored |
"//[***]\n1***2***3" | 6 | Delimiter of any length |
"//[*][%]\n1*2%3" | 6 | Multiple delimiters |
Tips
- Start with the simplest test case first (empty string)
- Add one requirement at a time
- Refactor after each passing test
- Consider edge cases like invalid input
- Think about how to handle the delimiter parsing