Skip to main content
Programming from zero

Split a log line into its parts

mediumStrings

Problem statement

A log line usually has a fixed structure at the start, a date, a time, a level, then a free-form message that can contain any number of spaces of its own: 2024-01-15 10:23:45 ERROR Database connection failed. Splitting on every space would break the message itself into separate words, losing the boundary between "where the fields end" and "where the message begins."

Common mistake: splitting on every space with no limit.

โ—ˆ DIAGRAM
Wrong: line.split(" ")
# โ†’ ["2024-01-15", "10:23:45", "ERROR", "Database", "connection", "failed"]

That gives six pieces instead of four, the message has been shredded into individual words. The fix is telling the split to stop after the first three spaces, so everything left over stays together as one message field.

Your task: given line = "2024-01-15 10:23:45 ERROR Database connection failed", split it into date, time, level, and message, then print each on its own line.

Expected output:

TEXT
2024-01-15
10:23:45
ERROR
Database connection failed

Approach

The idea is the same everywhere: split on spaces, but only three times, so the fourth piece keeps every space that's left.

  • Python's .split(" ", 3) takes a maxsplit argument directly, stopping after 3 splits and leaving the rest as one final piece.
  • Java's .split(" ", 4) takes a limit, the maximum number of pieces to return, so 4 here means "split at most 3 times."
  • C++ has no built-in limited split, so it's done manually: find the first three spaces with .find(), and take everything after the third one as the message in one .substr() call.
line = "2024-01-15 10:23:45 ERROR Database connection failed"
date, time, level, message = line.split(" ", 3)
print(date)
print(time)
print(level)
print(message)