Drill

ProblemsC# › validation

Read a quantity someone typed

easyvalidationParsingStringsC#

A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.

ValidQuantity(text: string) → int

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public int ValidQuantity(string text) {
    
}

Worked examples

CallResult
ValidQuantity("5")5
ValidQuantity(" 12 ")12
ValidQuantity("999")999
ValidQuantity("0")-1

Hint

Trim, reject an empty result, then check every remaining character before you convert.

Reference solution in C#
public int ValidQuantity(string text) {
    string t = text.Trim();
    if (t.Length == 0) return -1;
    foreach (char c in t) if (c < '0' || c > '9') return -1;
    long n = long.Parse(t);
    return (n >= 1 && n <= 999) ? (int) n : -1;
}

The same problem in another language

More validation problems in C#