String Calculator

Level: Intermediate

Concepts: Strings


Create a simple String calculator with a method that takes a string of numbers and returns their sum.

Requirements

  1. The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0).
  2. Allow the Add method to handle an unknown amount of numbers.
  3. Allow the Add method to handle new lines between numbers (instead of commas).
  4. Support different delimiters by starting the string with "//[delimiter]\n[numbers...]".
  5. Calling Add with a negative number will throw an exception "negatives not allowed" - and the negative that was passed.
  6. Numbers bigger than 1000 should be ignored.
  7. Delimiters can be of any length with the following format: "//[delimiter]\n".
  8. Allow multiple delimiters like this: "//[delim1][delim2]\n".
  9. 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