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.

#include

int main(){
    //1
    char inputStr[100];
    int i;

    //2
    printf("Enter your string : ");
    fgets(inputStr,100,stdin);

    //3
    int j = 0;

    //4
    for(i=0; inputStr[i] ;i++){
        //5
        if(inputStr[i] >= '0' && inputStr[i] <= '9'){
            inputStr[j] = inputStr[i];
            j++;
        }
    }

    //6
    inputStr[j] = '\0';

    //7
    printf("String after modification : ");
    printf("%s\n",inputStr);
}

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

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊