Home > Back-end >  Convert single characters of a string to elements of an integer array
Convert single characters of a string to elements of an integer array

Time:04-02

So I'm a newcomer to C and I've just learned about string after array. Now I'm trying to write a program that convert a string which consists of only integer numbers into an integer array.

For example let's say I have this string og[] and use fgets to get the input: og = 123456

Then I want to convert this '012345678' string into an array, let's say mod[] which be like:

mod[0] = 1; 
mod[1] = 2;
mod[2] = 3;
mod[3] = 4;
mod[4] = 5;
mod[5] = 6;

Is there any method to achieve this quickly with a function? If no, how could I write a function to convert this?

Thank you in advance.

CodePudding user response:

Use ASCII difference method in order to get required outcome:

For example let you are converting (char)1 to (int)1. So Subtract ASCII value of 1 by 0:

ie,'1'-'0'(since, 49-48=1 here 49 is ASCII value of '1' and 48 is of '0'). And at the end store it into integer variable.

By using above concept you code will be:

 int i=0;
char str []="123456789";
int strsize=(sizeof(str)/sizeof(char))-1;
int *arr=(int * )malloc(strsize*sizeof(int));
    // YOUR ANSWER STARTS HERE
while(str[i]!='\0'){
    arr[i]=str[i]-'0';
    i  ;
}

here size of str string is 10 thus subtracting 1 from it in order to get 9. here while loop moving till end of string (i.e '\0')

CodePudding user response:

If you are using an ASCII-based system (very likely) and you are only concerned with single digits, this is quite simple:

int main(void)
{
    char og[] = "123456";
    int *mod = calloc(strlen(og),sizeof(*mod));

    for (int i = 0; og[i];   i) {
        mod[i] = og[i] - '0';
    }
    // then whatever you want to do with this
}

This works because in ASCII, decimal digits are sequential and when the character is '0' and you subtract '0' (which is 48 in ASCII), you get the numerical value of 0; when the character is '1' (which is 49 in ASCII), you get the numerical value 1; and so on.

  • Related