String Calculator

Level: Intermediate 30–60 min

Concepts: Strings

Solutions: C# | TypeScript | Python


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

InputResultNotes
""0Empty string returns 0
”1”1Single number returns itself
”1,2”3Two numbers separated by comma
”1,2,3”6Multiple numbers separated by comma
”1\n2,3”6New line as delimiter
”//;\n1;2”3Custom delimiter
”-1,2”Exception: “negatives not allowed: -1”Negative numbers not allowed
”2,1001”2Numbers > 1000 are ignored
”//[]\n12***3”6Delimiter of any length
”//[][%]\n12%3”6Multiple 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

Reference Walkthrough

Full C#, TypeScript, and Python implementations live at tddbuddy-reference-katas/string-calculator. This is a Pedagogy mode kata: the commit log is the teaching, stepping through the TDD cycle commit-by-commit — red, green, refactor, reflect — with the gear visibly shifting from low (fake-it, triangulate) to middle (one scenario per cycle) to high (obvious implementation; later scenarios pass on arrival).

Unlike Bank Account (which ships in middle gear, one commit per language), String Calculator ships as the TDD arc itself: roughly twenty commits per language, each labeled with its cycle phase and gear. See the repo’s Gears section for why the gear shift is the real teaching point.