Separating integer by character

Asked

Viewed 1,700 times

8

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 to turn an array like this: {1, 2, 3, 4} that is, to separate the integer, because need for each number of that in a position of a matrix.

  • 1

    You want a character array (e.g..: '1') or whole (ex.: 1)? I answered for whole, but it’s easy to adapt if you want chars.

  • Even whole, it’s easier to manipulate.

2 answers

7


First you need, for each integer, to know how many decimal digits it occupies. If you have at hand a logarithm function, better, else go multiplying a variable by 10 until she’s bigger than the number:

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

Then just create the array with this size, and go picking 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 already explained in your other question, the C language offers no means of dynamically discovering the size of an array, so you need to store this information somewhere or use a null terminator when applicable. The above example does not do this, so be careful when adapting.

  • Valeu killed two doubts in one answer!

2

I’ve done this job 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 a compatible size array where the separate number will be placed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.