Hi. How are you all? Today I am sharing you a C program where I am showing you how we can separate integers from a string. For Example: Dhaka1212 or Dha12ka05. Now our problem is to separate the digits from the strings. Let’s see how we can solve this. Let’s check out the code first, then I’ll discuss about the code:
|7||char str1, str2;|
|8||int i, j=0, digits, len;|
|11||len = strlen(str1);|
First of all I added three header files. First one is “stdio.h” which is for standard input and output library. This header file contains input and output functions. Second one is for String Handling functions such as “strlen()” which is used later in this program. The “stdlib.h” defines four variable types, several macros and various functions. We used to for the “atoi()” function which is also used in this function.
We have two character type array one is “str1” & “str2”. “str1” is for getting the input from user and “str2” is for storing the integer digits. The size of the string is not a fact, actually we can define as much we are expecting the input is going to long. But, we should take the same size of string as it is not impossible to get the all characters are integer in a string.
“i” & “j” are declared for loop control purpose. “len” is find out the length of the string which will be needed later and “digits” is to finally store the Integer digits.
On line 10, we are expecting the input from the user. Then we find out the length of the string using library function ‘strlen()’. We done this cause then we do not need to check the whole character array. We will just check our string e.g. our string can be of 5 character, so what is the need for checking the whole array.
The first loop is for checking all the characters one by one as per our condition. In the first loop there is a ‘if’ condition which will check weather our character is integer or not? If this is a integer, then it will be stored in the “str2” array one after another in a continuous memory location.
Now we have the integers stored in a different array. But there is a problem. Follow line 17, we have initialized a character to another character array. That means we got the digits but our program is counting them as character. If we want to convert them to integer then have to use ‘atoi()’ (i.e. Alphabet to Integer). The ‘atoi()’ function will convert the digits to integer data type. On line 21, we stored the digits to an integer type variable ‘digits’ and then we just print it for the output.
Thank You. If you found any bug, please let me know. Please do not copy paste, try yourself. If I made anything confusing let me know. Happy Coding 🙂