Data and Formats · Lesson 10

Line-oriented text

Choose clear rules for whitespace and empty records.

How it works

A line-oriented format needs a policy for separators, blank lines, and whitespace around values. This example accepts both common newline forms by splitting on newline and trimming a trailing carriage return. It then discards empty trimmed lines and keeps the remaining labels in order. That policy is appropriate for a simple list, but it would destroy meaningful spaces in a fixed-width record or quoted field.

Document the format before normalizing input. Parsing should not silently reinterpret a file according to whatever makes a particular example pass; the same rules must apply to every row, including empty and boundary cases.

Add a name containing an internal space and verify that trimming preserves it. Then decide whether duplicate names or empty lines should be rejected rather than silently removed in a stricter import.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var text = " Ada\r\n\r\nLin \n";
var names = text.Split('\n').Select(line => line.Trim()).Where(line => line.Length > 0);
Console.WriteLine(string.Join(",", names));

Expected output

Ada,Lin
Try this
Whitespace normalization must follow the format’s rules.