Separate integer by character

7

I have a vector of integers: int nums[10] = { 1234, 4761814, 9161451, 14357 };

I want to know how to separate these numbers, for example, the first element turns a vector like this: {1, 2, 3, 4} ie separate the integer, because I need for each number in a position of an array.

    
asked by anonymous 08.10.2015 / 05:30

2 answers

7

First you need, for each integer, to know how many decimal digits it occupies. If you have a logarithm function at hand, let's either multiply a variable by 10 until it gets larger than the number:

int numero = 1234;
int qtosDigitos = 1;
int limite = 10;
while ( numero >= limite ) {
    qtosDigitos++;
    limite *= 10;
}

Then just create the array of this size, and go get the digits one by one:

int* digitos = (int*)malloc(qtosDigitos * sizeof(int));
for ( int i = 0 ; i < qtosDigitos ; i++ ) {
    limite /= 10;
    digitos[i] = (numero / limite) % 10;
}

Note: This solution only applies to non-negative numbers.

Now just iterate over the array and do this number by number:

int** digitosNums = (int**)malloc(tamanhoNums * sizeof(int*));
for ( int t = 0 ; t < tamanhoNums ; t++ ) {
    int numero = nums[t];
    ... // Código acima
    digitosNums[t] = digitos;
}

Note: As explained in your other question , the C language does not provide a means of dynamically finding the size of an array, so you need to save this information somewhere or use a null terminator when applicable. The above example does not do this, so be careful when adapting.

    
08.10.2015 / 06:08
1

I made this function for your problem:

void desmembrar(int num, int *array){
     int i=0, div = 10, prediv = 1, numchar = 0;
     while(num - numchar){
          int aux =  num % div;
          int dif = numchar;
          numchar = aux;
          aux -= dif;
          aux /= prediv;
          prediv = div;
          div *= 10;
          array[i] = aux;
          i++;    
     }
     //inverte o array
     numchar = -1; i = 0;
     for(numchar; prediv != 1; numchar++) prediv /=10;
     for(i ; i != numchar && numchar > i; i++){
        int aux = array[numchar];
        array[numchar] = array[i];
        array[i] = aux; numchar --;
     }    
}

Just pass by parameter the number you want to separate, and an array of compatible size where the separate number will be placed.

    
08.10.2015 / 15:44