🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Trim and Replace Words
Remove leading and trailing blanks and replace words safely in C, with proper buffer capacity checks.
What You Will Learn
- How to trim leading and trailing whitespace in place
- Why memmove is the right tool when regions overlap
- How to replace a word with a longer or shorter one into a separate buffer
- How to check capacity before every write and fail cleanly
- The difference between substring replacement and whole-word replacement
Prerequisites
- Lectures cp9_48 and cp9_49
- strlen, strncmp, memcpy and memmove basics
- Understanding of buffer size versus string length
Two string jobs show up in almost every real program: cleaning stray blanks from the ends of a line, and swapping one piece of text for another. In this lecture of our free C programming course you will learn how to trim whitespace and replace words in C, using nothing but the standard library. Both are essential in embedded C programming: a line from a serial console almost always arrives with a trailing newline or carriage return, and configuration strings often need a keyword swapped before they are applied.
The first function removes leading and trailing blanks in place. The second replaces every occurrence of one word with another, even when the replacement has a different length, which is the part that makes it interesting: the output may be longer than the input, so you must think about buffer size before you write a single byte.
Trim Leading and Trailing Blanks in C
Trimming has two halves. For the front, advance a pointer past blanks. For the back, shrink a length until the last character is not a blank. Then move the surviving bytes to the start of the buffer and terminate. We say blanks but mean whitespace: spaces, tabs, carriage returns and newlines are all garbage at the edges of a command line, and isspace recognises every one of them.
Why memmove and not memcpy
After the scan, the source (start) and the destination (the buffer start) live in the same array and may overlap. memcpy is not allowed to be used with overlapping regions; memmove is designed for exactly that case. Choosing the right one costs nothing and removes a whole class of bugs that appear only with certain input lengths.
| Function | Overlapping regions | Use it for |
|---|---|---|
memcpy | Undefined behaviour | Copying between two separate buffers |
memmove | Handled correctly | Shifting data inside one buffer |
strcpy | Undefined behaviour | Copying a terminated string to a separate buffer |
Design note: the function scans the length once with strlen after skipping the front, so the whole trim is O(n). No temporary buffer is needed, which is perfect for a small embedded target.
Replace Every Occurrence of a Word
The original exercise replaces one city name with its modern name inside a line of text. We use a configuration string instead, because it is closer to what firmware actually does: take mode=debug;log=debug and turn debug into release. The old word has five letters and the new one has seven, so the result is longer than the source and cannot be built in place in a buffer of the same size.
The Safe Design: Source In, Destination Out
The function takes the source, the old text, the new text, a separate destination buffer and the capacity of that buffer. It returns 0 on success and -1 when the result would not fit. Passing the capacity is the key to safety: the function checks before every write, so it can never run off the end of the destination.
Each branch asks the same question before writing: will the piece plus the terminator still fit? If the answer is no, the function jumps to a single cleanup label that sets the destination to an empty string and returns -1. A caller can then test one return value and never see a half built result.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static void trim_blanks(char *s)
{
char *start = s;
size_t len;
while (*start != '\0' && isspace((unsigned char)*start))
start++;
len = strlen(start);
while (len > 0 && isspace((unsigned char)start[len - 1]))
len--;
memmove(s, start, len);
s[len] = '\0';
}
static int replace_word(const char *src, const char *old, const char *rep,
char *dst, size_t cap)
{
size_t olen = strlen(old), rlen = strlen(rep), used = 0;
if (olen == 0 || cap == 0)
return -1;
while (*src != '\0') {
if (strncmp(src, old, olen) == 0) {
if (used + rlen + 1 > cap)
goto overflow;
memcpy(dst + used, rep, rlen);
used += rlen;
src += olen;
} else {
if (used + 2 > cap)
goto overflow;
dst[used++] = *src++;
}
}
dst[used] = '\0';
return 0;
overflow:
dst[0] = '\0';
return -1;
}
int main(void)
{
char padded[] = " \t uart0 ready \n";
char out[64], tiny[16];
const char *cfg = "mode=debug;log=debug";
trim_blanks(padded);
printf("trimmed : [%s]\n", padded);
if (replace_word(cfg, "debug", "release", out, sizeof out) == 0)
printf("replaced : %s\n", out);
if (replace_word(cfg, "debug", "release", tiny, sizeof tiny) != 0)
printf("tiny buf : result does not fit in %zu bytes\n", sizeof tiny);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o trim_replace trim_replace.c
./trim_replace
trimmed : [uart0 ready]
replaced : mode=release;log=release
tiny buf : result does not fit in 16 bytes
The first line shows brackets around the trimmed result so you can see that no blanks survive. The second line proves the replacement worked on both occurrences. The third line proves the safety check: with a 16 byte destination the 24 character result cannot fit, so the function refuses instead of overflowing.
This replaces substrings, not whole words. Replacing cat would also change category to xxegory. If you need real words, add the same left and right boundary check you learned in the counting lecture before you accept a match.
How Big Can the Result Get?
If a caller wants to size the destination exactly, count the matches first, then compute the final length: original length plus the number of matches times the difference between the new and old lengths. That gives a worst case you can allocate once. On systems without a heap, pick a fixed maximum, document it, and rely on the capacity check to fail safely.
| Old length | New length | Result size | Where to write it |
|---|---|---|---|
| Equal | Equal | Same as source | Can edit in place |
| Longer | Shorter | Smaller than source | In place with a read and write pointer |
| Shorter | Longer | Larger than source | Separate buffer with a capacity check |
Common Mistakes and Troubleshooting
- Trimming only spaces. A real input line often ends with
\r\n. Useisspace. - Using memcpy for the shift. It appears to work until the overlap is large enough to corrupt data. Use
memmove. - Ignoring the terminator when sizing the destination. Always reserve one extra byte.
- Replacing inside the destination while scanning it. If the new text contains the old text, you can loop forever. Scan the source, write to the destination.
- Empty old text. Matching an empty string succeeds at every position. Reject it up front, as the code does.
- Returning a pointer to a local buffer. The caller provides the buffer; the function never returns its own.
Best Practices, Performance and Security
- Bounds first. Pass the destination capacity and check it before every write. Many historic security bugs come from functions that did not.
- Prefer failing loudly. Returning -1 and clearing the output is better than truncating silently and processing a corrupted command.
- Performance. This version is O(n times m) because it compares at every position. For configuration sized strings that is perfectly fine; for large text use
strstrto jump to the next match. - Trim, then validate. Trim the input before comparing it with commands, otherwise
"start "will not equal"start"and your device will mysteriously ignore users. - Keep both functions testable. They have no global state, so a simple table of input and expected output covers them.
Practice Challenges
- Write
ltrimandrtrimas separate functions and havetrim_blankscall both. - Modify
replace_wordto return the number of replacements and to refuse when the destination overlaps the source. - Add the whole-word boundary check so that
debuginsidedebuggeris left alone.
Key Takeaways
- Trim by skipping the front, shrinking the back, then
memmoveand terminate. - Use
isspace, not just the space character. - Word replacement changes the length, so write to a separate buffer and pass its capacity.
- Check space before every write and fail cleanly with a return code.
- Substring replacement is not word replacement; add boundaries when you need words.
Conclusion
Trimming and replacement look small, but together they contain three lessons that carry into every later chapter: choose memmove when memory overlaps, treat the output buffer capacity as a first class parameter, and decide explicitly what a failure looks like. Code that follows those rules stays safe when the input surprises you.
Run the program with a longer replacement and a smaller destination and watch the safety check trigger. Then continue this free C tutorial with the next lecture, where we encode and decode text. It is a compact way to practise indexing, ranges and lookup tables for embedded C programming.
Frequently Asked Questions
How do I trim whitespace from a string in C?
Skip leading whitespace with a pointer, shrink the length while the last character is whitespace, then memmove the remaining bytes to the buffer start and terminate with '\0'.
Why use memmove instead of memcpy when trimming?
The source and destination are in the same array and can overlap. Only memmove is defined for overlapping memory.
How do I replace a word in a C string?
Scan the source; at each position compare with the old word, and copy either the replacement or one character into a separate destination buffer, checking capacity before each write.
Can I replace text in place if the new text is longer?
Not safely in the same buffer, because the string grows. Use a destination buffer large enough for the longer result, or move the tail first.
What does the function return when the output does not fit?
It returns -1 and leaves an empty string in the destination, so a single check protects the caller.
Is this useful in embedded Linux and firmware work?
Yes. Trimming serial input and rewriting configuration strings are routine in a free embedded C course project and in real products.
Keep Going With the Free Embedded C Course
EmbeddedPathashala teaches embedded C programming, Linux kernel development and device drivers for free. Pick the next lecture and keep your streak going.

2 Comments