codescracker
c++

C++ Program to Extract Numbers from String



« C++ Tutorial C++ Example »

This article provides some programs in C++ to extract all the numbers available in a string entered by user at run-time. These are the list of programs available in this article:

Extract Numbers from String using Character Array

The question is, write a program in C++ to extract and print numbers available in a string. The string must be entered by user. The program given below is its answer:

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

using namespace std;
int main()
{
   char str[100], num[100];
   int tot, i, j=0;
   cout<<"Enter the String: ";
   gets(str);
   tot = strlen(str);
   for(i=0; i<tot; i++)
   {
      if(str[i]>='0' && str[i]<='9')
      {
         num[j] = str[i];
         j++;
      }
   }
   cout<<endl<<"Numbers extracted from the String:"<<endl;
   for(i=0; i<j; i++)
      cout<<num[i]<<" ";
   cout<<endl;
   return 0;
}

The snapshot given below shows the initial output produced by above C++ program on extracting all the numbers available in a string entered by user:

c++ program extract numbers from string

Now supply the input say Hey 012, this is 394 from 329 codescracker as string and press ENTER key to extract and print all numbers available in the string like shown in the snapshot given below:

extract all numbers from string c++

Extract Numbers from String using Integer Array

This program does the same job as of previous program, but this program uses integer array, instead of character, to do the job.

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

using namespace std;
int main()
{
   char str[100];
   int tot, i, j=0, num[100];
   cout<<"Enter the String: ";
   gets(str);
   tot = strlen(str);
   for(i=0; i<tot; i++)
   {
      if(str[i]>='0' && str[i]<='9')
      {
         num[j] = str[i];
         num[j] = num[j] - 48;
         j++;
      }
   }
   if(j==0)
      cout<<"\nNumber not found in the string!";
   else if(j==1)
   {
      cout<<"\nOnly one number found in the string:";
      cout<<endl<<num[0];
   }
   else
   {
      cout<<"\nAll numbers extracted from the string.\n";
      cout<<"\nThe list of Numbers are:"<<endl;
      for(i=0; i<j; i++)
         cout<<num[i]<<" ";
   }
   cout<<endl;
   return 0;
}

Here is its sample run with user input codescracker as string:

extract numbers from string c++

Here is another sample run with user input codes0123cracker9 as string:

c++ extract get print numbers from string

Note - In above program, the statement num[j] = num[j] - 48; is used to convert the ASCII value to its equivalent character (number).

Note - The ASCII value of 0 is 48, 1 is 49, 2 is 50, ..., and 9 is 57. Means that, subtracting 48 from ASCII value, returns the number itself.

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker