C#
string manipulation
multi-character delimiter
split method
programming tutorial

How do I split a string by a multi-character delimiter in C?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C, splitting a string by a multi-character delimiter requires manual scanning because standard tokenizers like strtok are character-set based, not substring based. If delimiter is "||" or "<->", strtok cannot treat it as one atomic separator. A reliable solution uses strstr to locate delimiter occurrences and then slices segments carefully.

Core Sections

1) Why strtok is insufficient

strtok(s, "||") means split on any '|' character, not on the exact substring "||".

For exact multi-char separators, use substring search.

2) strstr-based splitter example

c
1#include <stdio.h>
2#include <string.h>
3
4void split_multi(const char *input, const char *delim) {
5    const char *start = input;
6    const size_t dlen = strlen(delim);
7
8    while (1) {
9        const char *pos = strstr(start, delim);
10        if (!pos) {
11            printf("token: %.*s\n", (int)strlen(start), start);
12            break;
13        }
14        printf("token: %.*s\n", (int)(pos - start), start);
15        start = pos + dlen;
16    }
17}

Usage:

c
split_multi("a||b||c", "||");

3) Returning allocated tokens

For reusable libraries, build dynamic array of allocated strings and return count.

c
// pattern: malloc token buffer, memcpy segment, null-terminate
// caller frees each token and token-array container

Define ownership contract explicitly to prevent leaks.

4) Edge-case behavior

Decide upfront:

  • consecutive delimiters produce empty tokens?
  • leading/trailing delimiters produce empty tokens?
  • delimiter empty string is invalid?

Document these rules because parsing behavior depends on business requirements.

Validation and Production Readiness

After implementing any fix or pattern from this topic, validate behavior using a repeatable workflow rather than ad hoc spot checks. The most reliable process has three stages: reproduce baseline behavior, apply one focused change, then verify both expected and adjacent scenarios. This avoids false confidence from a single green run and helps isolate which change actually solved the problem.

A practical command-driven template:

bash
1# 1) capture baseline output/state
2./run_case.sh > before.txt
3
4# 2) apply one focused change from this guide
5# edit code/config and keep the diff minimal
6
7# 3) verify behavior and compare outputs
8./run_case.sh > after.txt
9diff -u before.txt after.txt

If your project includes automated tests, convert the original failure into a regression test immediately. This is the fastest way to prevent the same issue from reappearing during later refactors, dependency upgrades, or environment changes.

bash
1# example quality gate sequence
2./lint.sh
3./test.sh
4./smoke.sh

Also validate edge cases explicitly. Many production defects occur not on the nominal path, but on boundary inputs such as empty collections, null/none values, unusual encodings, or large payloads. Define a compact table of edge scenarios and expected outcomes so reviewers can reproduce your checks quickly.

Before rollout, confirm environment parity. A fix that works in local development can fail in staging or production when runtime versions, OS behavior, file systems, networking, or resource limits differ. Capture version metadata and infrastructure assumptions in your PR or runbook.

bash
1# capture runtime context (example)
2python --version
3node --version
4dotnet --info

Finally, define rollback criteria before deployment. If metrics or logs indicate regressions, teams should know exactly which change to revert and what signals trigger that decision. This operational discipline turns one-off troubleshooting into a maintainable engineering practice and significantly reduces incident recovery time.

Common Pitfalls

  • Using strtok and expecting multi-character delimiter semantics.
  • Forgetting to null-terminate copied token buffers.
  • Leaking allocated memory in tokenization utilities.
  • Failing to define behavior for empty tokens and edge delimiters.
  • Passing empty delimiter and triggering undefined parsing logic.

Summary

To split by multi-character delimiter in C, use strstr-based scanning and explicit substring extraction. This gives precise separator semantics and full control over edge cases and memory ownership. With clear contracts and tests, custom splitters are reliable for parser and protocol workloads.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.