C program to remove all characters from a string keeping all numbers

C program to remove all characters from a string keeping all numbers :

In this C programming tutorial, we will learn how to remove all characters and keep all numbers in a user given string. The program will ask the user to enter one string, read the string and then it will modify it to hold only the numbers


int main(){
    char inputStr[100];
    int i;
    printf("Enter your string : ");
    int j = 0;
    for(i=0; inputStr[i] ;i++){
        if(inputStr[i] >= '0' && inputStr[i] <= '9'){
            inputStr[j] = inputStr[i];
    inputStr[j] = '\0';
    printf("String after modification : ");

Explanation :

The commented numbers in the above program denote the step number below :

1. Create one character array to store the user input string. Integer i is to use in the loop below.
2. Ask the user to enter the string. Read it using fgets and store in the variable inputStr.
3. Create one integer variable j to indicate the current position of the array. We are using two integer i and j. i will be used to scan character by character . j points to 0 at first. If any number is detected on the position pointed by i, we will place that number on index j of the array and increment the value of j by 1.
4. Start one for loop to scan the characters of the string.
5. Check if the current character is a number or not. If yes, place that character on position of j and increment the value of j.
6. After the loop is completed , set the current position of j to ’\0’. That means the end of the string.
7. Print out the string after the modification is completed.

Sample Output :

Enter your string : hello33 c448
String after modification : 33448

Enter your string : 123hello 456world7
String after modification : 1234567

Enter your string : 123456
String after modification : 123456

Leave a Reply