🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Sort, Abbreviate, Extract Strings
Sort characters, build acronyms and extract substrings in C with safe, reusable functions.
What You Will Learn
- How to sort the characters in a string with insertion sort and counting sort
- How to detect word starts and build an abbreviation
- How to extract a substring with proper bounds checks
- How to choose between algorithms for embedded C programming
- How to test boundary cases for string helpers
Prerequisites
- Lectures cp9_48 to cp9_51
- Arrays, loops and memcpy
- The difference between string length and buffer size
This lecture groups three small but instructive string exercises: putting the characters of a word into alphabetical order, building an abbreviation from the first letters of each word, and extracting a substring that starts at a given position and has a given length. If you are working through our free C programming course, these programs are where loops, comparisons and bounds checking finally come together. You will learn how to sort the characters in a string in C with two different algorithms, and how to write library quality helper functions for embedded C programming.
Each function takes a destination buffer and its size wherever it produces new text, and returns a value that tells the caller whether it worked. This is the habit that separates a classroom answer from a function you can safely ship in firmware.
Sort the Characters in a String in C
The exercise: given a word, rearrange its letters so they appear in alphabetical order. Characters in C are small integers, so sorting a string is exactly the same as sorting an array of numbers. We show two approaches because they teach different lessons.
Approach 1: Insertion Sort
Insertion sort keeps the left part of the string sorted. Take the next character, slide it left past every larger character, and drop it in place. It needs no extra memory and is quick for short strings, which is most of what you handle in firmware.
Approach 2: Counting Sort
There are only 256 possible byte values, so we can count how often each one occurs and then write the characters back in order. This is called counting sort. It makes just two passes over the data and never compares characters with each other, so its time is O(n + 256), regardless of how scrambled the input is.
| Property | Insertion sort | Counting sort |
|---|---|---|
| Extra memory | None | 256 counters (roughly 1 to 2 KB) |
| Time for n characters | O(n squared) worst, fast when nearly sorted | O(n + 256) always |
| Best for | Very short strings, tiny RAM | Long strings, many repeated letters |
| Stable behaviour | Yes | Not applicable for single bytes |
| Code size | Small | Small, but needs a table |
Why start the counting loop at 1? Value 0 is the terminator and never counts as a character. Starting at 1 means we never write a zero into the middle of the string.
Build an Abbreviation From Initial Letters
To abbreviate Universal Asynchronous Receiver Transmitter as UART you take the first letter of every word. The only real question is how to detect the start of a word. The answer is one flag: in_word. When a letter appears and the flag is off, you are at the start of a word, so you emit an uppercase letter and turn the flag on. When a non-letter appears, you turn the flag off.
Because hyphens and punctuation turn the flag off, inter-integrated circuit becomes IIC, which is exactly how engineers abbreviate it. The output buffer has a capacity too; we stop adding letters once it is full, but always write the terminator.
Extract a Substring Safely
The third exercise: copy n characters starting at position i. Standard C has no substring function, so you build one from memcpy. The interesting part is what to do with bad numbers. A start beyond the end of the string is an error. A length that runs past the end is clamped: we return what is available. If the destination is too small for the answer, we fail rather than truncate silently.
| Situation | What our function does | Return value |
|---|---|---|
| Start inside the string, length fits | Copies n characters | n |
| Length runs past the end | Copies up to the end | Characters copied |
| Start beyond the string length | Copies nothing | -1 |
| Destination too small | Copies nothing | -1 |
| Start equals the length | Copies zero characters, empty string | 0 |
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static void sort_chars_insertion(char *s)
{
size_t n = strlen(s);
for (size_t i = 1; i < n; i++) {
char key = s[i];
size_t j = i;
while (j > 0 && s[j - 1] > key) {
s[j] = s[j - 1];
j--;
}
s[j] = key;
}
}
static void sort_chars_counting(char *s)
{
size_t freq[256] = {0};
char *w = s;
for (const unsigned char *p = (const unsigned char *)s; *p; p++)
freq[*p]++;
for (int c = 1; c < 256; c++)
for (size_t k = 0; k < freq[c]; k++)
*w++ = (char)c;
*w = '\0';
}
static void make_acronym(const char *text, char *out, size_t cap)
{
size_t n = 0;
int in_word = 0;
for (; *text != '\0'; text++) {
if (isalpha((unsigned char)*text)) {
if (!in_word && n + 1 < cap)
out[n++] = (char)toupper((unsigned char)*text);
in_word = 1;
} else {
in_word = 0;
}
}
out[n] = '\0';
}
static int substr_copy(const char *s, size_t start, size_t n,
char *dst, size_t cap)
{
size_t len = strlen(s);
if (start > len || cap == 0)
return -1;
if (n > len - start)
n = len - start; /* clamp, like a forgiving API */
if (n + 1 > cap)
return -1;
memcpy(dst, s + start, n);
dst[n] = '\0';
return (int)n;
}
int main(void)
{
char a[] = "bluetooth", b[] = "bluetooth";
char acr[16], piece[16];
const char *file = "firmware_update.bin";
sort_chars_insertion(a);
sort_chars_counting(b);
printf("insertion : %s\ncounting : %s\n", a, b);
make_acronym("Universal Asynchronous Receiver Transmitter", acr, sizeof acr);
printf("acronym : %s\n", acr);
make_acronym("inter-integrated circuit", acr, sizeof acr);
printf("acronym : %s\n", acr);
printf("substr(9,6) -> %d [%s]\n",
substr_copy(file, 9, 6, piece, sizeof piece), piece);
printf("substr(9,100) -> %d [%s]\n",
substr_copy(file, 9, 100, piece, sizeof piece), piece);
printf("substr(50,2) -> %d\n",
substr_copy(file, 50, 2, piece, sizeof piece));
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o sort_abbr_sub sort_abbr_sub.c
./sort_abbr_sub
insertion : behloottu
counting : behloottu
acronym : UART
acronym : IIC
substr(9,6) -> 6 [update]
substr(9,100) -> 10 [update.bin]
substr(50,2) -> -1
Both sorting methods produce behloottu: the nine letters of bluetooth in alphabetical order, with the repeated o and t kept. (Note that sorting the letters of motivate gives aeimottv; the two t characters must both survive, which is a good test for your own solution.) The two acronyms come out as UART and IIC, and the three substring calls show an exact copy, a clamped copy and a rejected request.
Common Mistakes and Troubleshooting
- Losing repeated letters. If your sorted output is shorter than the input, you deduplicated by accident. A sort must keep every character.
- Using
intfor the loop index withstrlen. Mixing signed and unsigned types can make a loop run forever. Usesize_tconsistently. - Off-by-one with
start + n. Comparenwithlen - startinstead; adding first can overflow for large values. - Forgetting the terminator in the destination. Every function above writes it on every success path.
- Comparing signed chars. Characters above 127 can be negative on some platforms. For byte-accurate ordering, compare as
unsigned char. - Assuming ASCII order is alphabetical. All capital letters sort before all lowercase ones. Convert case first if you want a case-insensitive order.
Best Practices, Performance and Security
- Choose the algorithm by the data: insertion sort for short strings and tight RAM, counting sort when strings are long.
- Always pass the destination capacity into functions that produce text, and make failure visible through the return value.
- Clamp where it is natural (a length that runs long) and refuse where it is dangerous (a start past the end).
- Write tests for boundaries: empty string, start at zero, start at the length, length zero, destination size one.
- Avoid
strncpyfor substrings; it does not always terminate.memcpyplus an explicit terminator is clearer and safer.
Practice Challenges
- Sort the characters in descending order by changing one comparison.
- Write
is_anagramthat returns true if two words contain exactly the same letters, using counting sort ideas. - Add a
skip_wordsparameter to the abbreviation function so small words such as of and and are ignored.
Key Takeaways
- Sorting a string is sorting an array of bytes; keep every character.
- Insertion sort uses no extra memory; counting sort is linear with a 256 entry table.
- An
in_wordflag detects word starts for acronyms. - A safe substring function validates start, clamps length and checks destination size.
- Write the terminator on every success path and report failure through the return value.
Conclusion
Three small exercises, one common thread: strings are arrays, and arrays need careful ranges. Sorting taught you two ways of thinking about the same job, abbreviation taught the power of a single flag, and substring extraction taught how to be strict about inputs without being unhelpful.
Next, in this free C tutorial, we move from single strings to collections of strings: arrays of pointers for lookup tables, name sorting and multi-line input. That topic is the backbone of command tables in embedded C programming.
Frequently Asked Questions
How do I sort the characters of a string in C?
Treat the string as an array of small integers and apply a sort. Insertion sort needs no extra memory; counting sort tallies each byte value and rewrites the string in order.
Which is faster for sorting a string, insertion sort or counting sort?
Counting sort is linear and wins on long strings. Insertion sort is simple and fine for the short strings common in embedded work.
How do I create an acronym from a phrase in C?
Track whether you are inside a word. When a letter appears while the flag is off, add its uppercase form to the output and set the flag.
How do I extract a substring in C?
Check that the start is within the string, clamp the length, make sure the destination is large enough, then memcpy the bytes and write the terminator.
Why not use strncpy to get a substring?
strncpy may leave the result without a terminator and pads with zeros. memcpy plus an explicit terminator is predictable.
Do these exercises matter outside the classroom?
Yes. File name parsing, version strings and command abbreviations all use them, and they are standard material in a free embedded C course.
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