c
  1. c-program-to-remove-all-characters-in-a-string-except-alphabets

Program to Remove all Characters in a String Except Alphabets - (C Programs)

In this tutorial, we'll discuss how to write a C program to remove all characters in a string except alphabets. This can be useful in certain applications where you need to extract only the alphabetic characters from a string.

Syntax

The syntax of the program is as follows:

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

void removeNonAlphabetic(char* str);

int main()
{
    char str[100];

    printf("Enter a string: ");
    gets(str);

    removeNonAlphabetic(str);

    printf("Resultant string: %s", str);

    return 0;
}

void removeNonAlphabetic(char* str)
{
    int i, j;

    for (i = 0; str[i] != '\0'; ++i)
    {
        while (!((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0'))
        {
            for (j = i; str[j] != '\0'; ++j)
            {
                str[j] = str[j + 1];
            }
            str[j] = '\0';
        }
    }
}

Example

Suppose we have a string Hello123World!. The output of the program should be HelloWorld, with all non-alphabetic characters removed.

Output

Enter a string: Hello123World!
Resultant string: HelloWorld

Explanation

The program defines a function removeNonAlphabetic that takes a string as input and removes all non-alphabetic characters from it. The function iterates through each character in the string. If the character is not an alphabet, it is removed by shifting all subsequent characters one position to the left.

Use

This program can be useful in applications where you need to extract only the alphabetic characters from a string. It can be integrated with other programs that require only alphabetic characters, such as text analysis, data cleansing, and data mining.

Summary

In this tutorial, we discussed how to write a C program to remove all characters in a string except alphabets. We covered the syntax, example, explanation, use, and important points of the program. By removing all non-alphabetic characters from the input string, we can extract only the alphabetic characters, which can be useful in a variety of applications.

Published on: