C++ program to remove all numbers from a string

C++ program to remove all numbers from a string:

In this post, we will learn how to remove all numbers from a string in C++. This program will take one string as input from the user, remove all numbers from that string and print that newly created string.

The simplest way to solve this is by iterating through the characters of the string and removing all numbers from the string.

C++ program to remove all numbers from a string using loop:

In this method,

  • Iterate through the characters one by one
  • Add one flag to point to the current position of the string and one to scan the characters. Copy each character currently scanning to the current position. If a number is found, skip that number.
  • Finally, return the substring from the start position to current position of the string, which is the required string that holds only characters without any number.

Below is the complete C++ program:

#include <iostream>
#include <algorithm>
using namespace std;

string removeNumbers(string str)
{
    int current = 0;
    for(int i = 0; i< str.length(); i++){
        if(!isdigit(str[i])){
            str[current] = str[i];
            current++;
        }
    }

    return str.substr(0,current);
}

int main()
{
    string str;

    cout << "Enter the string : " << endl;
    getline(cin,str);

    cout << "Modified string : " << removeNumbers(str) << endl;
}

Here,

  • removeNumbers method takes one string as the parameter and removes all numbers from the string.
  • This method uses current to point to the current position in the string where we need to copy the iterating character.
  • The for loop iterates from the start character to the end character.
  • For each character, it checks if it is a number or not. If it is a number, it skips that.
  • Finally, it returns the substring from 0 to current
Enter the string : 
hello123 world
Modified string : hello world

Method 2: Using a loop and erase:

erase() method can be used to remove a character in a string. This method is not recommended because erase itself is an expensive operation. So, the complexity of this method is more than the previous one.

We will use one loop and use erase for all numbers found in the string. Below is the complete program:

#include <iostream>
#include <algorithm>
using namespace std;

string removeNumbers(string str)
{
    for(int i = 0; i< str.length(); i++){
        if(isdigit(str[i])){
            str.erase(i, 1);
            i--;
        }
    }

    return str;
}

int main()
{
    string str;

    cout << "Enter the string : " << endl;
    getline(cin,str);

    cout << "Modified string : " << removeNumbers(str) << endl;
}

Here,

  • if a digit is found, it calls erase to erase the character at that position.
  • It also decrements the value of i. Otherwise it will move to the next position.

It will print similar output as the above one.

You might also like: