🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Replace and Delete Characters
Edit C strings in place: replace characters, delete characters and strip spaces and delimiters without extra memory.
What You Will Learn
- Why only writable arrays may be edited and literals may not
- How to replace characters in place and return a count
- The read and write pointer technique for deleting characters
- How to remove spaces and a whole set of delimiters with strchr
- Mistakes that corrupt strings in embedded C programming
Prerequisites
- Lecture cp9_48: counting characters
- Pointers and char arrays
- Basic understanding of the null terminator
Reading a string is safe. Changing it is where C programmers get hurt. In this lecture of our free C programming course you will learn how to replace and delete characters in C strings in place, with no extra buffer, and how the same idea removes every space and delimiter from a line of text. These are everyday jobs in embedded C programming: turning a comma separated record into a clean token stream, sanitising a device name before you store it in flash, or stripping separators from a serial number.
The source exercises ask for three functions: replace every occurrence of one character with another, delete every occurrence of a character, and print a line after removing all spaces and delimiters. All three share one principle: the string is an array you own, so you may rewrite it, but you must keep the terminator where it belongs.
Editing a String in Place: What Must Be True First
Before any edit, ask who owns the memory. A string you want to modify has to live in writable storage, which means a char array or a heap block. A string literal assigned to a pointer is not writable on most platforms; writing to it is undefined behaviour and usually crashes or, on a microcontroller, silently does nothing because the literal lives in flash.
| Declaration | Storage | Safe to modify? |
|---|---|---|
char a[] = "node-1"; | Array on stack or in RAM, initialised from the literal | Yes, a is your private copy |
const char *p = "node-1"; | Pointer to a literal, usually in read-only memory | No, the type says so |
char *p = "node-1"; | Same literal, but the type hides the danger | No, undefined behaviour if you write |
char *p = malloc(n); | Heap block you filled yourself | Yes, until you free it |
Rule of thumb: if the function modifies the string, its parameter is char * and the caller must pass an array. If it only reads, the parameter is const char *. The type documents the contract and lets the compiler catch mistakes.
Replace Characters in a C String
Replacement is the easiest edit because the length never changes. Walk the string, and wherever the current character equals the old one, overwrite it with the new one. Returning the number of replacements is cheap and makes the function easy to test, so we do that.
Nothing moves; one cell changes. The terminator stays at index 5 before and after, so the string keeps the same length.
Delete Characters Without Leaving Holes
Deletion is harder because the string gets shorter and the characters after a removed one must slide left. The beginner approach is to shift the whole tail of the string by one position for every deleted character, which is slow (O(n squared) in the worst case) and easy to get wrong. The professional approach uses two indexes in a single pass, usually called read and write.
- The read pointer visits every character exactly once.
- The write pointer marks where the next surviving character belongs.
- If the character is a keeper, copy it to the write position and advance write. If it is the unwanted one, do nothing; read advances alone.
- At the end, store the terminator at the write position.
Because the write position can never run ahead of the read position, you never overwrite a character you have not looked at yet. That invariant is what makes the algorithm correct, and it is a pattern you will reuse for filtering buffers of every kind.
Remove All Spaces and Delimiters
The last exercise is the same compaction with a different keeper test. Instead of comparing with one character, we ask whether the character belongs to a set of unwanted characters. The library function strchr does the lookup: it returns a pointer if the character is in the set and NULL otherwise. The set is passed as a string, so the caller decides what counts as a delimiter: " ,.;!-" today, " \t:" tomorrow.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static size_t replace_char(char *s, char from, char to)
{
size_t changed = 0;
for (; *s != '\0'; s++) {
if (*s == from) {
*s = to;
changed++;
}
}
return changed;
}
/* Two-index compaction: r reads every char, w writes only the keepers. */
static size_t delete_char(char *s, char ch)
{
char *w = s;
size_t removed = 0;
for (const char *r = s; *r != '\0'; r++) {
if (*r == ch)
removed++;
else
*w++ = *r;
}
*w = '\0';
return removed;
}
static void remove_set(char *s, const char *set)
{
char *w = s;
for (const char *r = s; *r != '\0'; r++)
if (strchr(set, *r) == NULL)
*w++ = *r;
*w = '\0';
}
int main(void)
{
char a[] = "sensor-1,sensor-2,sensor-3";
char b[] = "Hello, World! v2.0 - ready;";
printf("original : %s\n", a);
printf("replaced : %zu -> %s\n", replace_char(a, '-', '_'), a);
printf("deleted : %zu -> %s\n", delete_char(a, ','), a);
printf("\nbefore : %s\n", b);
remove_set(b, " ,.;!-");
printf("after : %s\n", b);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o edit_chars edit_chars.c
./edit_chars
original : sensor-1,sensor-2,sensor-3
replaced : 3 -> sensor_1,sensor_2,sensor_3
deleted : 2 -> sensor_1sensor_2sensor_3
before : Hello, World! v2.0 - ready;
after : HelloWorldv20ready
Read the output line by line. Three dashes were replaced, then two commas were deleted, leaving a string that is two bytes shorter. In the second demo every space, comma, full stop, exclamation mark, semicolon and hyphen disappeared and the remaining letters and digits closed up around the gaps.
A subtle trap in remove_set: calling strchr(set, c) with c == 0 returns a pointer to the set’s own terminator, not NULL. The loop never passes the terminator, so we are safe here, but if you ever extend the loop to include it, handle it separately.
Why Not Build a New String Instead?
You could allocate a second buffer and copy the survivors into it. That is cleaner when you must keep the original, but on a small microcontroller RAM is precious, and in-place compaction needs no extra memory at all. The trade-off is simple.
| Approach | Extra RAM | Original preserved | Good for |
|---|---|---|---|
| In-place two pointers | None | No | Sanitising input buffers, tokenising received lines |
| Copy to a new buffer | Up to the original length | Yes | When you need before and after, or the source is read-only |
| Shift the tail per deletion | None | No | Avoid: slow and error prone |
Common Mistakes and Troubleshooting
- Forgetting the final terminator. After compaction the string is shorter. If you do not write
'\0'at the write position, old bytes beyond it remain and the string looks unchanged at the end. - Passing a literal.
delete_char("a,b", ',')modifies read-only memory. Declare an array:char buf[] = "a,b";. - Confusing the character and the string.
','is one character;","is a two byte string.delete_charwants the first,remove_setwants the second. - Using one index for both reading and writing while deleting. You will skip characters or copy garbage.
- Case sensitivity. Replacing
adoes not touchA. Usetoloweron both sides if you want case-insensitive behaviour.
Best Practices, Performance and Security
- Return how many characters changed or were removed; it makes unit tests trivial and lets callers react.
- Single pass, O(n), zero allocation: the in-place pattern is the right default on resource constrained targets.
- Document that the function modifies its argument. A comment above the function costs nothing and prevents misuse.
- Sanitise before you trust: stripping separators from user supplied text is the first step of input validation, but it is not validation by itself. Check the length and the final content as well.
- When the cleaned string is used as a file name or a command, never rely on character removal alone to make it safe. Prefer a whitelist of allowed characters.
Practice Challenges
- Write
replace_setthat maps every character of a delimiter set to a single space, then count how many fields remain. - Write
squeeze_charthat collapses runs of the same character (for example repeated spaces) into one, using the read/write idea. - Modify
delete_charso it deletes only the first n matches and stops.
Key Takeaways
- Only arrays and heap blocks may be edited; string literals are read-only.
- Replacement keeps the length, so one pass and no movement are needed.
- Deletion uses a read pointer and a write pointer, then a new terminator.
- Removing a set of delimiters is the same compaction with a set membership test.
- Return a count and document that the function modifies its argument.
Conclusion
Replacing and deleting characters teach the most important idea in C string editing: the string is just bytes in memory, and you are responsible for the terminator. The read and write pointer pattern gives you a fast, allocation free tool that you will meet again in tokenisers, parsers and protocol decoders.
Practise by feeding the programs tricky inputs: an empty string, a string made only of delimiters, a string with no match. When all three behave, you are ready for the next lecture in this free C tutorial, where we trim blanks and replace whole words, a problem in which the length of the string can change.
Frequently Asked Questions
How do I replace a character in a C string?
Loop over the string and assign the new character wherever the current one matches. The string must be a writable array, not a string literal.
How do I delete a character from a string in C?
Use two indexes in one pass: copy each character that should stay to the write position, skip the ones to delete, and write the terminator at the end.
Why does modifying a string literal crash my program?
Literals may be stored in read-only memory. Copy the text into a char array first and edit the array.
How can I remove all spaces and punctuation from a string?
Run the same compaction loop and keep a character only if it is not found in a set of unwanted characters, using strchr or isalnum.
Is in-place editing safe on a microcontroller?
Yes, as long as the buffer is writable and you keep the terminator. It uses no extra RAM, which is why embedded C programming favours it.
Where can I learn more C string handling for free?
This free embedded C course continues with trimming, word replacement and encoding in the next lectures.
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