Alphanumeric Abbreviations of a String in C Program?

In C programming, generating alphanumeric abbreviations of a string means creating all possible combinations where some characters can be replaced with numbers representing the count of omitted characters. For example, "HELLO" can be abbreviated as "HE2O" where "2" represents the two omitted characters "LL".

Syntax

void printAbbreviation(const char* s, int index, int max_index, char* str, int str_len);

Algorithm

The recursive algorithm works as follows −

printAbbreviation(s, index, max, str) ?
begin
   if index is same as max, then
      print str
   end if
   add s[index] at the last of str
   printAbbreviation(s, index + 1, max, str)
   delete last character from str
   count := 1
   if str is not empty, then
      if the last character of str is a digit, then
         add last digit with the count value
         delete last character from str
      end if
   end if
   add count after the str
   printAbbreviation(s, index + 1, max, str)
end

Example

Here's a complete C implementation that generates all alphanumeric abbreviations of a given string −

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void printAbbreviation(const char* s, int index, int max_index, char* str, int str_len) {
    if (index == max_index) {
        str[str_len] = '\0';
        printf("%s
", str); return; } /* Include current character */ str[str_len] = s[index]; printAbbreviation(s, index + 1, max_index, str, str_len + 1); /* Skip current character and add count */ int count = 1; int new_str_len = str_len; if (str_len > 0 && isdigit(str[str_len - 1])) { count += (str[str_len - 1] - '0'); new_str_len--; } str[new_str_len] = (char)(count + '0'); printAbbreviation(s, index + 1, max_index, str, new_str_len + 1); } void printCombination(const char* input_str) { if (strlen(input_str) == 0) { return; } char result[100]; printAbbreviation(input_str, 0, strlen(input_str), result, 0); } int main() { char str[] = "HELLO"; printf("All alphanumeric abbreviations of '%s':
", str); printCombination(str); return 0; }
All alphanumeric abbreviations of 'HELLO':
HELLO
HELL1
HEL1O
HEL2
HE1LO
HE1L1
HE2O
HE3
H1LLO
H1LL1
H1L1O
H1L2
H2LO
H2L1
H3O
H4
1ELLO
1ELL1
1EL1O
1EL2
1E1LO
1E1L1
1E2O
1E3
2LLO
2LL1
2L1O
2L2
3LO
3L1
4O
5

How It Works

  • For each character, we have two choices: include it or skip it
  • When including a character, we add it to the result string
  • When skipping characters, we replace them with a digit representing the count
  • If the previous character was already a digit, we combine the counts
  • The recursion explores all possible combinations

Conclusion

This algorithm generates all possible alphanumeric abbreviations using recursion with backtracking. The time complexity is O(2^n) where n is the string length, as each character has two choices.

Updated on: 2026-03-15T11:44:31+05:30

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements