How to remove digits from string in C++

In this article, we are going to learn how to remove digits from a string in C++. Strings are an array of characters. The main difference between a character array and a string is that a string ends with a special character ‘\0’ or null character. A string declaration is similar to that of a one-dimensional array.

char string_name[size];

Let us discuss a real-time application for removing digits from a string. Cryptography is a method of protecting information and communications using codes so that only the people for whom the information is intended can read and process it. One way of doing this is that the encrypter can add numbers and special characters in the message and the receiver can decode this message by running the code/algorithm to show just the characters.

Remove digits from a string in C++

Let’s take the help of an example.

Input: h45e9ll45o8 wor34l35d

Output: helloworld

Code Implementation:

#include <iostream>
using namespace std;

int main()
    char str[100]; 
    int i, j; 
    cout<<"String before modification: "<<str<<endl;
    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];
    cout<<"String after modification: "<<str;
    return 0;



In the above code, the string is modified using a loop. If the character in the string is not null or an alphabet, then all the characters to the right are shifted towards the left by 1. This is done using j in the inner for loop. This leads to the removal of the characters that aren’t alphabets from the string.

I hope, you have understood how our program works to remove digits from a string in C++.

Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.

You may also learn,

Last word from a string

Leave a Reply

Your email address will not be published. Required fields are marked *